Reputation: 3787
I have this d3 line chart:
http://jovansfreelance.com/bikestats/d3/tipsy.php
You can see the JS source there, it's located at http://jovansfreelance.com/bikestats/d3/js/d3LineChart.js.
I added an alert to the page so it will alert the data object when the page loads. As you see, I have multiple values for each year. That's fine and the graph looks like it should, except the values from 2012 shouldn't connect back to the values from 2006.
Basically, my question is, how do I disconnect the graph at certain places? Every time the x-axis value is 2012, I need to disconnect the graph (not show the line from 2012 back to 2006).
Upvotes: 0
Views: 1413
Reputation: 2704
You need to change the structure of your data. As written now, the generateData()
function takes the 20 values and pushes them onto the same array. This results in the data variable being an array of objects with the following structure:
data = [
{ value: "253.65", date: "2006"},
{ value: "269.67", date: 2007 },
...
];
This data structure is causing d3 to draw a single, connected line from 2006 to 2012 then back to 2006 again two times.
To get three different lines, you need to break the data up so that d3 recognizes each series as a distinct object. Consider getting your data into a strucuture like this:
data = [
{
name: "series01",
points: [
{ value: "253.65", date: "2006"},
{ value: "269.67", date: 2007 },
...
]
},
{
name: "series02",
points: [
{ value: "253.65", date: "2006"},
{ value: "269.67", date: 2007 },
...
]
},
{
name: "series01",
points: [
{ value: "253.65", date: "2006"},
{ value: "269.67", date: 2007 },
...
]
}
];
Of course if you do this, you will need to rewrite the other d3 components do deal with the fact that the x and y values for your circles are nested within the points property of each series object. See multiple lines d3 for more about drawing multiple lines.
Added in reply to a comment:
The size loop that assigns rawdata elements to data one at a time is the problem. It works against the way d3 handles data. In the first loop, d3 enters 7 paths and circles for the 7 elements in the data array.
.enter()
only adds new svg elements based on changes in the data array. If no key is used, changes are driven by array length. Since the length of the data array does not change on the second and third times through the loop, no new paths are added.
To get all three lines, remove the loop, use .data(rawdata)
for the data and change the line 'd' attribute to .attr('d', line(d.points))
.
Unfortunately, this will mess up the circles. For help with drawing circles and lines on the same data take a look at Mike Bostocks svg:g element suggestion in this google groups discussion https://groups.google.com/forum/?fromgroups=#!topic/d3-js/8XLzUYLoFnY
Upvotes: 1