I created a bar chart in D3 and I'm trying to sort the bars in a bar chart in ascending order on clicking, and on descending on clicking again. I added in the necessary code for sorting at the end of the code snippet but nothing happens on clicking (the bars don't sort). Not sure what I'm missing here, any help would be appreciated!
<script>
var margin = {top: 40, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
})
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.call(tip);
d3.tsv("data/bar-graph-tooltips.tsv", type, function(error, data) {
x.domain(data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.on("click", function() {sortBars();});
//Define sort order flag
var sortOrder = false;
//Define sort function
var sortBars = function() {
//Flip value of sortOrder
sortOrder = !sortOrder;
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.ascending(a, b);
} else {
return d3.descending(a, b);
}
})
.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
});
};
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
</script>
You need to set the values that need to be sorted in the a, b, here:
.sort(function(a, b) {
if (sortOrder) {
return d3.ascending(a, b);
} else {
return d3.descending(a, b);
}
Something like: a.value, b.value but that depends on how your tsv is structured
Related
I have a real simple horizontally stacked bar chart with 3 bars that are all on the same scale (i.e. each 0 to 100 with the stacked bars consisting of numbers that make up 100).
When trying to update my data nothing appears to happen. I've not been able to figure out how to update the data and it's been driving me crazy.
Relevant Code:
<body>
<div id='updateTest'>
Update Data
</div>
<div id='chart'></div>
<script>
$( document ).ready(function() {
$( "#updateTest" ).click(function() {
updateData();
console.log(allData[count]);
});
});
var institution;
// Set up the SVG data
var allData = ["data.csv","data2.csv","data3.csv"];
var count = 0;
var margin = {top: 20, right: 20, bottom: 145, left: 115},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.rangeRoundBands([height, 0], .1);
var x = d3.scale.linear()
.rangeRound([0, width]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888"]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.format(".2s"));
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Bind initial shown data to the SVG
d3.csv(allData[count], function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) {
return key !== "Institution";
}));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {name: name, y0: y0, y1: y0 += +d[name]};
});
d.total = d.ages[d.ages.length - 1].y1;
});
data.sort(function(a, b) { return b.total - a.total; });
y.domain(data.map(function(d) { return d.Institution; }));
x.domain([0, d3.max(data, function(d) { return d.total; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("x", -32)
.attr("y", -112)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Institution");
institution = svg.selectAll(".institution")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(0," + y(d.Institution) + ")"; });
institution.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("height", y.rangeBand())
.attr("x", function(d) { return x(d.y0); })
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 28 + ")"; });
legend.append("rect")
.attr("x", -20)
.attr("y", 190)
.attr("width", 25)
.attr("height", 25)
.style("fill", color);
legend.append("text")
.attr("x", 10)
.attr("y", 203)
.attr("dy", ".35em")
.style("text-anchor", "left")
.text(function(d) { return d; });
});
/* updateData()
* Rebinds the SVG to a new dataset
*/
function updateData() {
// Iterate through the data
var newData;
if (count === allData.length - 1)
count = 0;
else
count++;
newData = allData[count];
// Get the data again
d3.csv(allData[count], function(error, data) {
data.forEach(function(d) {
d.close = +d.close;
});
// Make the changes
institution.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("height", y.rangeBand())
.attr("x", function(d) { return x(d.y0); })
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.style("fill", function(d) { return color(d.name); });
});
}
</script>
</body>
My CSV files:
data.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,15,35,50
Nonprofit,11,48,41
Public,26,16,58
data2.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,23,33,44
Nonprofit,28,12,60
Public,12,8,80
data3.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,61,22,17
Nonprofit,7,43,50
Public,41,19,40
The main bit is in the updateData() function. I am able to create the chart and display data but I do not understand transitioning the data...
I'm getting no errors in the console and it's properly cycling the data.
The problems is with d.ages in the update function. You basically need the same setup that you have for the initial plot. So I added the following in the d3.csv block of your update function:
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {name: name, y0: y0, y1: y0 += +d[name]};
});
d.total = d.ages[d.ages.length - 1].y1;
});
institution = svg.selectAll(".institution")
.data(data);
The class name for institution was set to g for some reason, and I changed that to institution. Also, you do not need .enter().append("rect") at this point. Finally I added a transition and duration.
I have created a plunk, with all your csv files included: http://plnkr.co/edit/CYFNWZKuiLo9gFps49e9?p=preview
Hope this helps.
I'm making a sortable d3 bar chart based on Scott Murray's tutorial, but he doesn't explain how to sort the x-axis labels along with the bars, and I haven't been able to figure it out despite various attempts. Here's my code; the relevant function is "sortBars" near the bottom, but I've included the rest for context.
(Here's a fiddle, but I can't seem to translate the data correctly from my JSON.)
The bar heights are data.days (which are numbers, i.e. number of days); the labels are data.names. How do I sort the labels?
function retirements(presidents){
var data = presidents;
var margin = {top: 20, right: 20, bottom: 180, left: 80},
width = 1100 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.names)
.rangeBands([0, width], .1);
var y = d3.scale.linear()
.domain([0, Math.ceil(d3.max(data.days)/1000)*1000])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d + " days";
})
var svg = d3.select(".container")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.call(tip);
var barWidth = width / data.days.length;
svg.selectAll("rect")
.data(data.days)
.enter().append("rect")
// this might be affected:
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
.attr("y", function(d) { return y(d); })
.attr("height", function(d) { return height - y(d) + 1; })
.attr("width", barWidth - 1)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.9em")
.attr("dy", ".25em")
.attr("transform", "rotate(-50)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "-6em")
.attr("dx","-15em")
.style("text-anchor", "end")
.text("Days");
var sortOrder = false;
var sortBars = function() {
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.descending(a, b);
} else {
return d3;
}
})
.transition()
.duration(1000)
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
$("#descending").on("click", function(){
sortOrder = true;
sortBars();
});
$("#chronological").on("click", function(){
sortOrder = false;
sortBars();
});
};
First of all rather than having 2 different arrays of presidents and its data.
Lets make it into single object so tat sorting is easy.
var newData = [];
data.names.forEach(function(d, i) {
newData.push({
name: d,//now object will have a name
days: data.days[i],//days will hold the president data
id: i //id of the record for chronology sorting
})
});
Now for sorting do this:
var sortBars = function() {
if (sortOrder){
//sort on basis of date
var sorted = newData.sort(function(a, b) {
return d3.descending(a.days, b.days);
});
} else {
//sort on basis of id
var sorted = newData.sort(function(a, b) {
return d3.ascending(a.id, b.id);
});
}
//set the domain post sorting
x.domain(sorted.map(function(d) {
return d.name;
}))
//sort the bars
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.descending(a.days, b.days);
} else {
return d3.ascending(a.id, b.id);
}
});
//make transition
var transition = svg.transition().duration(750),
delay = function(d, i) {
return i * 50;
};
//transition dor xa axis labels
transition.select(".x.axis")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.9em")
.attr("dy", ".25em")
.attr("transform", "rotate(-50)")
.delay(delay);
//transition for bars.
transition.selectAll("rect")
.attr("transform", function(d, i) {
return "translate(" + i * barWidth + ",0)";
});
}
Working code here
Hope this helps!
I was trying to make a d3 example from http://bl.ocks.org/mbostock/3887051 modified with my data. I use concepts similar to example. I didn't have problems with acquiring the data, but there's an unexpected identifier error.
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("datatest.csv", function(error, data) {
var inflasiTahun = d3.keys(data[0]).filter(function(key) { return key !== "tahun"; });
data.forEach(function(d) {
d.inflasi = inflasiTahun.map(function(name) { return {name: name, value: parseFloat(d[name])}; });
});
x0.domain(data.map(function(d) { return d.tahun; }));
x1.domain(inflasiTahun).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.inflasi, function(d) { return d.value; }); })
svg.append("g") //this is the error
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Inflasi");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x0(d.tahun) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.inflasi; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
});
</script>
I dont know In the console, the unexpected identifier points to this:
svg.append("g") //this is the error
You forgot to close the y.domain([ with ]); on the following line:
y.domain([0, d3.max(data, function(d) { return d3.max(d.inflasi, function(d) { return d.value; }); })
Tools like JSLint and JSHint as well as proper indentation can help you in tracking down this kind of errors.
I'm trying to add a zoom ability to a historical line chart I've built using a custom data object. I've been using http://codepen.io/brantwills/pen/igsoc/ as a template. The chart is rendered but when I try zooming there are two errors:
Error: Invalid value for path attribute d=""
Uncaught TypeError: undefined is not a function (in the last transform, translate of the last part of the zoomed function)
JSFiddle: http://jsfiddle.net/dshamis317/sFp6Q/
This is what my code looks like:
function renderHistoricalData(data) {
var parseDate = d3.time.format("%Y%m%d").parse;
data.forEach(function(d) { d.date = parseDate(d.date); });
// data.sort(function(a,b) { return a.date - b.date; });
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 1200 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var line = d3.svg.line()
.interpolate("basis")
// .defined(function(d) { return d.y!=0; })
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.sentiment); });
var svg = d3.select("#historical_chart").append("svg")
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
var sites = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, sentiment: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(sites, function(c) { return d3.min(c.values, function(v) { return v.sentiment; }); }),
d3.max(sites, function(c) { return d3.max(c.values, function(v) { return v.sentiment; }); })
]);
var site = svg.selectAll(".site")
.data(sites)
.enter().append("g")
.attr("class", "site");
site.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
site.append("text")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sentiment (%)");
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll('path.line').attr('d', line);
sites.selectAll('.site').attr("transform", function(d) {
return "translate(" + x(d.date) + "," + y(d.sentiment) + ")"; }
);
}
}
Thank you!
Alright, let's walk through each thing.
To start with, in zoomed, the last transform doesn't need to be there. In the original, it's there to move the circles, which you don't have.
Also important, your edit on path.line sets d to the wrong function. If you look at what you're setting d to when you first make it, it should be the same, as a general rule of thumb, so it should be function(d) { return line(d.values); }, not just line.
Now, for the actual reason it's disappearing.
Your scale extent is calculated based off the original domain. However, you don't set the domain until AFTER you call scaleExtent, which means your scaling is all based on the default. It's not actually disappearing, it's being compressed to the left hand side of the graph. If you remove your x axis, you'll see the colored smear of all your data flattened against the side.
Move all your domain calculations to above where you build your scale, and it'll be fine.
To make things a bit more concrete:
function renderHistoricalData(data) {
var parseDate = d3.time.format("%Y%m%d").parse;
data.forEach(function(d) { d.date = parseDate(d.date); });
// data.sort(function(a,b) { return a.date - b.date; });
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 1200 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
var sites = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, sentiment: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(sites, function(c) { return d3.min(c.values, function(v) { return v.sentiment; }); }),
d3.max(sites, function(c) { return d3.max(c.values, function(v) { return v.sentiment; }); })
]);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var line = d3.svg.line()
.interpolate("basis")
// .defined(function(d) { return d.y!=0; })
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.sentiment); });
var svg = d3.select("#historical_chart").append("svg")
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var site = svg.selectAll(".site")
.data(sites)
.enter().append("g")
.attr("class", "site");
site.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
site.append("text")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sentiment (%)");
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll('path.line').attr('d', function(d) { return line(d.values); });
}
}
If you want to text to move, you can give it an easily identifiable class, and then update it in zoomed.
Giving it a class:
site.append("text")
.attr("class", "lineLabel")
Updating it in zoomed:
svg.selectAll(".lineLabel")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
});
This will just make it follow the ends of the lines, but you can modify whatever attributes you like to get the wanted effects.
I'm trying to create a multiline graph using D3, and I keep running across the same error
Error: Problem parsing d="MNaN,450LNaN,0LNaN,450LNaN,450LNaN,0LNaN,0"
Which seems to occur when I try to graph my line:
city.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
I'm trying to graph a single line at the moment with the following data set:
{"name":"application_active_users","values":[{"value":0,"end_time":"2013-06-14T11:00:00.000Z"},{"value":1,"end_time":"2013-06-15T11:00:00.000Z"},{"value":0,"end_time":"2013-06-16T11:00:00.000Z"},{"value":0,"end_time":"2013-06-17T11:00:00.000Z"},{"value":1,"end_time":"2013-06-18T11:00:00.000Z"},{"value":1,"end_time":"2013-06-19T11:00:00.000Z"}]}
I'm assuming something is wrong with my datasource. Does anyone see an immediate issue with how my datasource is set up?
Here is a portion of the D3 code. The entire code is here http://jsfiddle.net/hy4Hz/.
var payload;
var storedMetrics = [];
var metricCount = 1;
var graphData = [];
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//var parseDate = d3.time.format("%Y-%m-%d").parse;
//var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse;
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S").parse;
var color = d3.scale.category10();
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function (d) {
return x(d.end_time);
})
.y(function (d) {
return y(d.value);
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(
data, function (d) {
return d.end_time;
}));
y.domain([
d3.min(metrics, function (c) {
return d3.min(c.values, function (v) {
return v.value;
});
}),
d3.max(metrics, function (c) {
return d3.max(c.values, function (v) {
return v.value;
});
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Temperature (ºF)");
var city = svg.selectAll(".city")
.data(metrics)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line")
.attr("d", function (d) {
return line(d.values);
})
.style("stroke", function (d) {
return color(d.name);
});
city.append("text")
.datum(function (d) {
return {
name: d.name,
value: d.values[d.values.length - 1]
};
})
.attr("transform", function (d) {
return "translate(" + x(d.value.end_time) + "," + y(d.value.value) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.text(function (d) {
return d.name;
});
It looks like your x.domain() might not be set up correctly. The first argument to d3.extent should be data.values.