Here is the JSON structure I am working with:
[{
"city": "roma",
"giornata": [{"hour": 0, "vscore": 2.691172504799798, "sscore": 37476.67912706408}, {"hour": 1, "vscore": 2.691172504799798, "sscore": 37476.67912706408}, {"hour": 2, "vscore": 2.6911859886310534, "sscore": 37477.76228681598}, {"hour": 3, "vscore": 2.692891756586413, "sscore": 37633.63745016247}, {"hour": 4, "vscore": 2.7490858604464163, "sscore": 40331.835034215015}, {"hour": 5, "vscore": 3.6348376398556206, "sscore": 29087.830074293775}, {"hour": 6, "vscore": 5.227711033677134, "sscore": 40951.01373374646}, {"hour": 7, "vscore": 5.437638544676074, "sscore...
I want to create a dynamic d3 line chart using this data, where each city represents a line on the chart. For example:
One line for "roma" with X-axis as "hour" and Y-axis as "vscore"
Another line for "milan" with X-axis as "hour" and Y-axis as "vscore"
The challenge is to create the d3.svg.line() dynamically from this JSON structure.
Currently, my code only works with a single line:
var margin = {
top: 20,
right: 20,
bottom: 50,
left: 40
},
width = 900 - margin.left - margin.right,
height = 290 - margin.top - margin.bottom;
// Set the ranges
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left").innerTickSize(-width)
.outerTickSize(0)
.tickPadding(10);
// Define the line
// Struggling to generate lines dynamically
var valueline = d3.svg.line()
.interpolate("basis")
.x(function (d) {
return x(d.hour);
})
.y(function (d) {
return y(d.vscore);
});
// Adds the svg canvas
var svg = d3.select("#dailyChart")
.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.json("data/ranking_sscore.json", function(error, data) {
data = data[0].giornata
data.forEach(function (d) {
d.hour = d.hour;
d.vscore = +d.vscore;
});
x.domain(data.map(function (d) {
return d.hour;
}))
y.domain([0, d3.max(data,
function (d) {
return Math.max(d.vscore);
})]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data))
.style("stroke", 1);
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 15)
.attr("x", 0)
.attr("dy", ".35em")
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
})
Any help would be appreciated. Thank you!