I'm trying to create a basic d3 pie chart with a legend. I'm following the examples in two different tutorials and somehow code from one example isn't playing well with the other. What I'm trying to do is set an ordinal scale's domain so I can use that to create a legend.
On the following line, I set the domain. If I step through the code, I can see that immediately after I get ["HEURISTIC", "ADWARE", "COMPANY_BLACK_LIST", "PUP", "SUSPECTED_MALWARE", "KNOWN_MALWARE"]. This is exactly what I want.
color.domain(labels)
However, if I keep stepping through, once I reach the following line, the domain changes to ["HEURISTIC", "ADWARE", "COMPANY_BLACK_LIST", "PUP", "SUSPECTED_MALWARE", "KNOWN_MALWARE", 0, 1, 2, 3, 4, 5]
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
QUESTION: What is causing those six extra items to be inserted into the domain?
Code (http://jsfiddle.net/tonicboy/2urZY/5/):
var w = 150,
h = 100,
r = 50,
color = d3.scale.category20c(),
dataset = [{"name":"HEURISTIC","value":65},{"name":"ADWARE","value":75},{"name":"COMPANY_BLACK_LIST","value":9},{"name":"PUP","value":34},{"name":"SUSPECTED_MALWARE","value":14},{"name":"KNOWN_MALWARE","value":156}],
labels = _.pluck(dataset, "name");
color.domain(labels);
var chart = d3.select("#pie_chart")
.append("svg:svg")
.data([dataset])
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", "0 0 " + w + " " + h)
.attr("preserveAspectRatio", "xMinYMin meet");
var vis = chart.append("g")
.attr("transform", "translate(" + (w - r) + "," + r + ")");
var arc = d3.svg.arc()
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.value; });
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
var legend = chart.append("g")
.attr("class", "pie-legend")
.selectAll("g")
.data(color.domain())
.enter()
.append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 7 + ")"; });
legend.append("rect")
.attr("width", 5)
.attr("height",5)
.style("fill", color);
legend.append("text")
.attr("x", 8)
.attr("y", 9)
.text(function(d) { return d; });
Here is what the chart looks like so far:
You're setting your ordinal scale domain with strings, but then calling it with index numbers. If you ask an ordinal scale for a value that isn't currently in its domain, it will add it to the domain and assign it the next value in the range (or recycle the range values if it runs out).
Original code:
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
Should be
arcs.append("svg:path")
.attr("fill", function(d, i) {return color( d.data.name); } )
.attr("d", arc);
The d value is the object created by the pie chart function; it stores the original data object as d.data. The name from that data is one of the values used in the color scale domain.
Updated fiddle: http://jsfiddle.net/2urZY/6/
Related
This is my first time using d3.js, so please bear with me. I am implementing this inside of a vue.js file as pure javascript.
I am trying to make a scatter plot with zooming capabilities. So far I have everything nearly working, but when I zoom I notice that the x-axis isn't scaling properly, but the y-axis is working properly. For instance, when looking at the original plot, a point may be at around 625 on the x-axis, but after zooming in the same point will be less than 600. This is not happening with the y-axis - those points scale properly. I am assuming that something is wrong with the scaling of the x-axis in my zoom function, but I just can't figure it out. Please take a look, and let me know if you can see where I went wrong.
Edit: I should mention that this is using d3.js version 7.4.4
<template>
<div id="reg_plot"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
name: 'regCamGraph',
components: {
d3
},
methods: {
createSvg() {
// dimensions
var margin = {top: 20, right: 20, bottom: 30, left: 40},
svg_dx = 1400,
svg_dy =1000,
chart_dx = svg_dx - margin.right - margin.left,
chart_dy = svg_dy - margin.top - margin.bottom;
// data
var y = d3.randomNormal(400, 100);
var x_jitter = d3.randomUniform(-100, 1400);
var d = d3.range(1000)
.map(function() {
return [x_jitter(), y()];
});
// fill
var colorScale = d3.scaleLinear()
.domain(d3.extent(d, function(d) { return d[1]; }))
.range([0, 1]);
// y position
var yScale = d3.scaleLinear()
.domain(d3.extent(d, function(d) { return d[1]; }))
.range([chart_dy, margin.top]);
// x position
var xScale = d3.scaleLinear()
.domain(d3.extent(d, function(d) { return d[0]; }))
.range([margin.right, chart_dx]);
console.log("chart_dy: " + chart_dy);
console.log("margin.top: " + margin.top);
console.log("chart_dx: " + chart_dx);
console.log("margin.right: " + margin.right);
// y-axis
var yAxis = d3.axisLeft(yScale);
// x-axis
var xAxis = d3.axisBottom(xScale);
// zoom
var svg = d3.select("#reg_plot")
.append("svg")
.attr("width", svg_dx)
.attr("height", svg_dy);
svg.call(d3.zoom().on("zoom", zoom)); // ref [1]
// plot data
var circles = svg.append("g")
.attr("id", "circles")
.attr("transform", "translate(200, 0)")
.selectAll("circle")
.data(d)
.enter()
.append("circle")
.attr("r", 4)
.attr("cx", function(d) { return xScale(d[0]); })
.attr("cy", function(d) { return yScale(d[1]); })
.style("fill", function(d) {
var norm_color = colorScale(d[1]);
return d3.interpolateInferno(norm_color)
});
// add y-axis
var y_axis = svg.append("g")
.attr("id", "y_axis")
.attr("transform", "translate(75,0)")
.call(yAxis).style("font-size", "20px")
// add x-axis
var x_axis = svg.append("g")
.attr("id", "x_axis")
.attr("transform", `translate(${margin.left}, ${svg_dy - margin.bottom})`)
.call(xAxis).style("font-size", "20px")
function zoom(e) {
// re-scale y axis during zoom
y_axis.transition()
.duration(50)
.call(yAxis.scale(e.transform.rescaleY(yScale)));
// re-scale x axis during zoom
x_axis.transition()
.duration(50)
.call(xAxis.scale(e.transform.rescaleX(xScale)));
// re-draw circles using new y-axis scale
var new_xScale = e.transform.rescaleX(xScale);
var new_yScale = e.transform.rescaleY(yScale);
console.log(d);
x_axis.call(xAxis.scale(new_xScale));
y_axis.call(yAxis.scale(new_yScale));
circles.data(d)
.attr('cx', function(d) {return new_xScale(d[0])})
.attr('cy', function(d) {return new_yScale(d[1])});
}
}
},
mounted() {
this.createSvg();
}
}
</script>
Interestingly enough, after I set the clip region to prevent showing points outside of the axes the problem seemed to resolve itself. This is how I created the clip path:
// clip path
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", "0")
.attr("y", "0")
.attr('width', chart_dx)
.attr('height', chart_dy);
And I then added that attribute to the svg when plotting the data like this:
svg.append("g").attr("clip-path", "url(#clip)")
Updated clip path with plot data section:
// clip path
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", "0")
.attr("y", "0")
.attr('width', chart_dx)
.attr('height', chart_dy);
// plot data
var circles = svg.append("g")
.attr("id", "circles")
.attr("transform", "translate(75, 0)")
.attr("clip-path", "url(#clip)") //added here
.selectAll("circle")
.data(d)
.enter()
.append("circle")
.attr("r", 4)
.attr("cx", function(d) { return xScale(d[0]); })
.attr("cy", function(d) { return yScale(d[1]); })
.style("fill", function(d) {
var norm_color = colorScale(d[1]);
return d3.interpolateInferno(norm_color)
});
I ended up resolving this issue. I have updated the original post to show what worked for me.
Basically, after adding the clip region things started to work properly.
// clip path (this is the new clip region that I added. It prevents dots from being drawn outside of the axes.
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", "0")
.attr("y", "0")
.attr('width', chart_dx)
.attr('height', chart_dy);
// plot data
var circles = svg.append("g")
.attr("id", "circles")
.attr("transform", "translate(75, 0)")
.attr("clip-path", "url(#clip)") //added clip region to svg here
.selectAll("circle")
.data(d)
.enter()
.append("circle")
.attr("r", 4)
.attr("cx", function(d) { return xScale(d[0]); })
.attr("cy", function(d) { return yScale(d[1]); })
.style("fill", function(d) {
var norm_color = colorScale(d[1]);
return d3.interpolateInferno(norm_color)
});
I've been having a bunch of trouble with a pie chart I've been trying to make. I finally have the outer ring working, but the inner ring only displays a few of the pieces (out ring has 3, inner ring has 6 but displays 3).
Does anyone know what might be wrong with this code? Both systems work fine on their own, but for whatever reason they don't work when I put them together.
The wedges for 20, 10 and 5 are the ones that don't display, and it happens that way every single time.
The name of the class ("arc") doesn't seem to matter, either.
function makeDonut(svg) {
var boundingBox = d3.select(svg).node().getBoundingClientRect();
var h = boundingBox.height;
var w = boundingBox.width;
/***** donut chart *****/
var data = [25, 40, 55];
// arbitrary data
var outerRadius = w/3;
var innerRadius = 3*(outerRadius/4);
var arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.pie();
// order: gold, silver, bronze
var color = d3.scaleOrdinal()
.range(['#e5ce0c', '#e5e4e0', '#a4610a']);
var arcs = d3.select(svg).selectAll("g.arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.attr("stroke", "white")
.style("stroke-width", "0.5px")
.on('mouseover', function(d) {
d3.select(this).attr('opacity', .7);
})
.on('mouseleave', function(d) {
d3.select(this).attr('opacity', 1);
});
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
/************ piechart ************/
var dataset = [ 5, 10, 20, 45, 6, 25 ];
// arbitrary dataset
var outerRadius2 = 0.75 * (w/3);
var innerRadius2 = 0;
var arc2 = d3.arc()
.innerRadius(innerRadius2)
.outerRadius(outerRadius2);
var pie2 = d3.pie();
var color2 = d3.scaleOrdinal(d3.schemeCategory10);
var arcs2 = d3.select(svg).selectAll("g.arc")
.data(pie2(dataset))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");
//Draw arc paths
arcs2.append("path")
.attr("fill", function(d, i) {
return color2(i);
})
.attr("d", arc2);
arcs2.append("text")
.attr("transform", function(d) {
return "translate(" + arc2.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
}
The D3 enter method creates elements in the DOM where needed so that for every item in the data array there is an appropriate element in the DOM.
For your donut chart, which you draw first, you selectAll("g.arc") - there are no g elements with the class arc, you have an empty selection. So when you use the enter method, D3 creates one element for every item in the data array. Everything chained to .enter(), without a .merge() method, only affects these entered elements.
For your pie chart, which you draw second, you selectAll("g.arc") - however, now there are three g elements with the class arc. So when you use the enter method here, the enter selection does not included elements for the first three items in the data array: they already exist. Instead these first three elements are included in the update selection.
This functionality is core to the D3 enter/update/exit cycle.
If you want to enter everything, and aren't updating or exiting data points, then you can simply use .selectAll(null) which will create an empty selection, for which an enter selection will create an element for every item in the data array.
If you wanted to modify these wedges/arcs later, you could differentiate the two, either by entering them in different g elements (eg: g1.selectAll("g.arc") and g2.selectAll("g.arc"). Alternatively, you could give them different class names based on whether pie or donut, as below:
var svg = d3.select("svg");
var boundingBox = svg.node().getBoundingClientRect();
var h = boundingBox.height;
var w = boundingBox.width;
/***** donut chart *****/
var data = [25, 40, 55];
// arbitrary data
var outerRadius = w/3;
var innerRadius = 3*(outerRadius/4);
var arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.pie();
// order: gold, silver, bronze
var color = d3.scaleOrdinal()
.range(['#e5ce0c', '#e5e4e0', '#a4610a']);
var arcs = svg.selectAll("donut")
.data(pie(data))
.enter()
.append("g")
.attr("class", "donut")
.attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.attr("stroke", "white")
.style("stroke-width", "0.5px")
.on('mouseover', function(d) {
d3.select(this).attr('opacity', .7);
})
.on('mouseleave', function(d) {
d3.select(this).attr('opacity', 1);
});
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
/************ piechart ************/
var dataset = [ 5, 10, 20, 45, 6, 25 ];
// arbitrary dataset
var outerRadius2 = 0.75 * (w/3);
var innerRadius2 = 0;
var arc2 = d3.arc()
.innerRadius(innerRadius2)
.outerRadius(outerRadius2);
var pie2 = d3.pie();
var color2 = d3.scaleOrdinal(d3.schemeCategory10);
var arcs2 = svg.selectAll(".pie")
.data(pie2(dataset))
.enter()
.append("g")
.attr("class", "pie")
.attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");
//Draw arc paths
arcs2.append("path")
.attr("fill", function(d, i) {
return color2(i);
})
.attr("d", arc2);
arcs2.append("text")
.attr("transform", function(d) {
return "translate(" + arc2.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=500 height=400></svg>
I have used d3 to create a pie chart. It works nicely, but, when the values of two elements' data are equal, it's showing the same color. How can I fix this problem?
function graph_pie_value(data, id, height, width){
d3.select(id).selectAll("svg").remove();
var radius = Math.min(width, height)/2;
var color = d3.scale.category20c();
var pie = d3.layout.pie()
.sort(null)
.value(function(d){return d.value;});
var arc = d3.svg.arc()
.outerRadius(radius-75)
.innerRadius(0);
var svg = d3.select(id).append("svg")
.attr("height", height)
.attr("width", width)
.append("g")
.attr("transform", "translate("+width/2+","+height/2+")");
svg.append("text").attr("class", "title_text").attr("x", 0)
.attr("y", -height/6*2).style("font-size", "14px").style("font-weight", 600)
.style("z-index", "19")
.style("text-anchor", "middle")
.text("Market Participation Value");
var totalValue=d3.nest()
.rollup(function(d){
return d3.sum(d,function(d){return +d.value;});
})
.entries(data);
data.forEach(function(d){
d.value = +d.value;
d.percent = +(d.value/totalValue*100);
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.attr("fill", function(d){return color(d.value);});
console.log(pie);
g.append("text")
.attr("transform", function(d){
var c = arc.centroid(d);
var x = c[0];
var y = c[1];
var h = Math.sqrt(x*x+y*y);
return "translate("+(x/h*(radius-30))+","+(y/h*(radius-30))+")";
})
.attr("dy", "0.35em")
.attr("class", "percent")
.style("text-anchor", "middle")
.text(function(d){return d.data.percent.toFixed(2)+"%";});
g.append("path")
.style("fill", "none")
.style("stroke", "black")
.attr("d", function(d)
{
var c = arc.centroid(d);
var x = c[0];
var y = c[1];
var h = Math.sqrt(x*x+y*y);
return "M"+(x/h*(radius-73))+","+(y/h*(radius-73))+"L"+(x/h*(radius-50))+","+(y/h*(radius-50));
});
var legend = svg.selectAll(".legend")
.data(data)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate("+(150-width+i*60)+"," + (height-70) + ")"; });
legend.append("rect")
.attr("x", width/2-150)
.attr("y", 50-height/2)
.attr("width", 12)
.attr("height", 12)
.style("fill", function(d){return color(d.value)});
legend
.append("text")
.attr("class", "legend")
.attr("x", width/2-130)
.attr("y", 60-height/2)
.attr("dy", ".10em")
.style("text-anchor", "start")
.text(function(d) { return d.symbol; });
return;
}
Here is the data format:
var data = [
{"symbol":"MSFT","value":14262751},
{"symbol":"CSCO","value":12004177}
]
It creates no problem in arc color, but when these two values are equal...
var data = [
{"symbol":"MSFT","value":14262751},
{"symbol":"CSCO","value":14262751}
]
...then the pie chart shows the same arc color.
The reason that when two values are equal, their corresponding slices have the same color is because you are setting the color based on value:
g.append("path")
.attr("d", arc)
.attr("fill", function(d){return color(d.value);});
Instead, set the color based on the index i of the data (which D3 also passes the callback function in this situation), like this:
g.append("path")
.attr("d", arc)
.attr("fill", function(d, i){return color(i);});
This will give you a pie chart with multiple colors, even if the slices have the same value:
I am new to D3 and my requirement is to get multiple line graphs and provide tooltips for them.
I could get the multiple line graphs to appear but i am going wrong in getting multiple tooltip points.
I am new to javascript as well. So any help will be much appreciated.
Here is my code.
<script>
function showData(obj, d) {
var coord = d3.mouse(obj);
var infobox = d3.select(".infobox");
// now we just position the infobox roughly where our mouse is
infobox.style("left", (coord[0] + 200) + "px" );
infobox.style("top", (coord[1] - 130) + "px");
$(".infobox").html(d);
$(".infobox").show();
}
function hideData() {
$(".infobox").hide();
}
var xx,yy;
function xx(e) {
return x(e.date); };
function yy(e) {
return y(e.returns); };
var draw = function() {
var margin = {top:100,left:200,right:200,bottom:100},
width = 1150 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d").parse;
x = d3.time.scale().range([0,width]);
y = d3.scale.linear().range([height,0]);
//values of the axis is plotted here
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var svg = d3.select("#chart").append("svg")
.attr("width" , width + margin.left + margin.right)
.attr("height" , height + margin.top + margin.bottom)
.attr("pointer-events" , "all")
.append("g")
//this is the line that positions the graph
.attr("transform" , "translate(" + margin.left + "," + margin.top +") ");
var activeReturns = new Array();
var passiveReturns = new Array();
var D3Obj = new Array();
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.returns);});
d3.json("d3.v3/sample1.json",function(error,result) {
result.data.forEach(function(d){
var arObj = new Object();
arObj.date = parseDate(d.date);
arObj.returns = +d.returns;
var prObj = new Object();
prObj.date = parseDate(d.date);
prObj.returns = +d.ticker_performance;
activeReturns.push(arObj);
passiveReturns.push(prObj);
});
D3Obj.push(activeReturns);
D3Obj.push(passiveReturns);
// this is where i tell that the line graph to be done
x.domain(d3.extent(D3Obj[0], function(d) {return d.date ;} ));
y.domain(d3.extent(D3Obj[0], function(d) {return d.returns ;} ));
svg.append("g")
.attr("class" , "x axis")
.call(xAxis)
.attr("transform","translate(0 ,"+ height + ")")
svg.append("g")
.attr("class" , "y axis")
//this is where yaxis line is added
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
svg.selectAll(".line")
.data(D3Obj)
.enter().append("path")
.attr("class","line")
.attr("d",line)
//this is where i am adding the tooltips
//tooltip for 1st line
svg.selectAll("circle")
.data(D3Obj[0])
.enter().append("circle")
.attr("fill", "red")
.attr("r", 2)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) { showData(this, d.returns);})
.on("mouseout", function(){ hideData();});
//tooltip for 2nd line - this is where i think i am going wrong.
svg.selectAll("circle")
.data(D3Obj[1])
.enter().append("circle")
.attr("fill", "steelblue")
.attr("r", 2)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) { showData(this, d.returns);})
.on("mouseout", function(){ hideData();});
});
$("#chart").append("<div class='infobox' style='display:none;'>Test</div>");
};
</script>
When you are creating the second point, nothing actually happens. The .data() function will try to match the data elements you pass to what you have selected (in this case one circle) and will succeed here. This means that your enter selection is empty and nothing happens.
The d3 way is to pass in all the data you want to use to create elements at once and handle accordingly in the functions to set attributes etc. That is, your code should look something like
svg.selectAll("circle")
.data(D3Obj)
.enter().append("circle")
.attr("fill", function(d, i) { if(i == 0) { return "red"; } else { return "steelblue"; } })
.attr("r", 2)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) { showData(this, d.returns);})
.on("mouseout", function(){ hideData();});
This will create two circles and attach the corresponding listeners to them.
How do I make my line x-axis based on date in d3.js?
I am attempting to teach myself how to use d3.js. I've been looking at the examples that come with it and have been attempting to recreate the line graph using json delivered data. I'm able to feed the data into the line graph, but the x-axis is supposed to be a date instead of a number. The date format that I'm using is MM/DD/YY, but the graph plots everything at 0. My json data is coming across fine, but I'm having trouble figuring out how to plot the x coordinates. This was taken straight from the line.js that comes in the d3.js examples folder when downloaded. The date portion doesn't do the trick. I'm hoping someone can point me to an example or be able to explain how I can make it work.
d3.json('jsonChartData.action',
function (data) {
console.log(data);
var w = 450,
h = 275,
p = 30,
x = d3.scale.linear().domain([0, 100]).range([0, w]),
y = d3.scale.linear().domain([0, 100]).range([h, 0]);
var vis = d3.select("body")
.data([data])
.append("svg:svg")
.attr("width", w + p * 2)
.attr("height", h + p * 2)
.append("svg:g")
.attr("transform", "translate(" + p + "," + p + ")");
var rules = vis.selectAll("g.rule")
.data(x.ticks(5))
.enter().append("svg:g")
.attr("class", "rule");
rules.append("svg:line")
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", h - 1);
rules.append("svg:line")
.attr("class", function(d) { return d ? null : "axis"; })
.attr("y1", y)
.attr("y2", y)
.attr("x1", 0)
.attr("x2", w + 1);
rules.append("svg:text")
.attr("x", x)
.attr("y", h + 3)
.attr("dy", ".71em")
.attr("text-anchor", "middle")
.text(x.tickFormat(10));
rules.append("svg:text")
.attr("y", y)
.attr("x", -3)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(y.tickFormat(10));
vis.append("svg:path")
.attr("class", "line")
.attr("d", d3.svg.line()
.x(function(d) { return x(d3.time.days(new Date(d.jsonDate))); })
.y(function(d) { return y(d.jsonHitCount); }));
vis.selectAll("circle.line")
.data(data)
.enter().append("svg:circle")
.attr("class", "line")
.attr("cx", function(d) { return x(d3.time.days(new Date(d.jsonDate))); })
.attr("cy", function(d) { return y(d.jsonHitCount); })
.attr("r", 3.5);
});
JSON as printed out by my action:
[{"jsonDate":"09\/22\/11","jsonHitCount":2,"seriesKey":"Website Usage"},`{"jsonDate":"09\/26\/11","jsonHitCount":9,"seriesKey":"Website Usage"},{"jsonDate":"09\/27\/11","jsonHitCount":9,"seriesKey":"Website Usage"},{"jsonDate":"09\/29\/11","jsonHitCount":26,"seriesKey":"Website Usage"},{"jsonDate":"09\/30\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/03\/11","jsonHitCount":3,"seriesKey":"Website Usage"},{"jsonDate":"10\/06\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/11\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/12\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/13\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"10\/14\/11","jsonHitCount":5,"seriesKey":"Website Usage"},{"jsonDate":"10\/17\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/18\/11","jsonHitCount":6,"seriesKey":"Website Usage"},{"jsonDate":"10\/19\/11","jsonHitCount":8,"seriesKey":"Website Usage"},{"jsonDate":"10\/20\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"10\/21\/11","jsonHitCount":4,"seriesKey":"Website Usage"},{"jsonDate":"10\/24\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"10\/25\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"10\/27\/11","jsonHitCount":3,"seriesKey":"Website Usage"},{"jsonDate":"11\/01\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"11\/02\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"11\/03\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"11\/04\/11","jsonHitCount":37,"seriesKey":"Website Usage"},{"jsonDate":"11\/08\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"11\/10\/11","jsonHitCount":39,"seriesKey":"Website Usage"},{"jsonDate":"11\/11\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"11\/14\/11","jsonHitCount":15,"seriesKey":"Website Usage"},{"jsonDate":"11\/15\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"11\/16\/11","jsonHitCount":5,"seriesKey":"Website Usage"},{"jsonDate":"11\/17\/11","jsonHitCount":4,"seriesKey":"Website Usage"},{"jsonDate":"11\/21\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"11\/22\/11","jsonHitCount":3,"seriesKey":"Website Usage"},{"jsonDate":"11\/23\/11","jsonHitCount":11,"seriesKey":"Website Usage"},{"jsonDate":"11\/24\/11","jsonHitCount":2,"seriesKey":"Website Usage"},{"jsonDate":"11\/25\/11","jsonHitCount":1,"seriesKey":"Website Usage"},{"jsonDate":"11\/28\/11","jsonHitCount":10,"seriesKey":"Website Usage"},{"jsonDate":"11\/29\/11","jsonHitCount":3,"seriesKey":"Website Usage"}]`
You're trying to use d3.scale.linear() for dates, and that won't work. You need to use d3.time.scale() instead (docs):
// helper function
function getDate(d) {
return new Date(d.jsonDate);
}
// get max and min dates - this assumes data is sorted
var minDate = getDate(data[0]),
maxDate = getDate(data[data.length-1]);
var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);
Then you don't need to deal with the time interval functions, you can just pass x a date:
.attr("d", d3.svg.line()
.x(function(d) { return x(getDate(d)) })
.y(function(d) { return y(d.jsonHitCount) })
);
Working fiddle here: http://jsfiddle.net/nrabinowitz/JTrnC/