Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - D3 Non-Continuous Dates Domain Gives Gaps on X-Axis

I want to plot some time series data that is not continuous (gaps in the dates for weekends, holidays, etc..). It's daily data.

The data looks something like:

date,value
1/2/15,109.33
1/5/15,106.25
1/6/15,106.26
1/7/15,107.75
1/8/15,111.89
1/9/15,112.01
1/12/15,109.25
1/13/15,110.22
...

So I define my x and y scales:

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

And set the domain from my source data:

x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.value; }));

The problem however, is that my dates have gaps in them. And my x-axis now includes those missing dates (d3.time.scale() does this automatically I guess because it maps to a continuous range?).

.extent() finds the max and min values in date then .domain() returns those max and min values as the range for the x-axis. But im not sure how to handle gaps and return the non gap dates to the range.

So my question is: How can I have my x-axis range only include the dates that are in my data set? And not "fill in the blanks". Should I play with the d3.time.scale().range() ? or do I need to use a different scale?

What is the correct way to do this? Can someone please point me in the right direction or give some example? Thank you!

Also please, I want to solve with with just plain d3 and javascript. I am not interested in using any 3rd party abstraction libraries.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Lars Kotthof points out, you can create an ordinal x axis, which "looks" like a time scale. Assuming you want to plot your time series as a line, here is an example how to do it: http://jsfiddle.net/ee2todev/3Lu46oqg/

If you want to customize your format for the dates, e.g. respresent the date as day (of the week), day and month you have to convert your string to a date first. I added one example which formats the dates in a common German format. But you can easily adjust the code to your needs. http://jsfiddle.net/ee2todev/phLbk0hf/

Last, but not least, you can use

axis.tickValues([values])

to choose the dates you want to display. See also: https://github.com/mbostock/d3/wiki/SVG-Axes#tickFormat


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...