Reputation: 1190
Trying to build a linechart (multiple lines). Initial data has been an array of object such as:
[{
2010: 8236.082,
countryName: "Afghanistan"
}]
Each line required an array of x/y pairs [[x,y],[x,y]]. My x and y are year and amount of emissions. This means I had to restructure my data it to make it look like this:
[
{
country: "Afganistan",
emissions: [
{ year: 2019, amount: 8236.082 }
]
}
]
However this doesn't work for me. Is the problem in the domain? Please help.
//Define full width, full height and margins
let fullWidth = 600;
let fullHeight = 700;
let margin = {
top: 20,
left: 70,
bottom: 100,
right: 10
}
//Define line chart with and height
let width = fullWidth - margin.left - margin.right;
let height = fullHeight - margin.top - margin.bottom;
//Define x and y scale range
let xScale = d3.scaleLinear()
.range([0, width])
let yScale = d3.scaleLinear()
.range([0, height])
//Draw svg
let svg = d3.select("body")
.attr("width", fullWidth)
.attr("height", fullHeight)
.append("svg")
.append("g")
d3.json("https://api.myjson.com/bins/izmg6").then(data => {
console.log(data);
//Structure data so should be an array of arrays etc [[x,y], [x,y], [x,y]]
let years = d3.keys(data[0]).slice(0, 50);
console.log(years);
let dataset = [];
data.forEach((d, i) => {
let myEmissions = [];
years.forEach(y => {
if (d[y]) {
myEmissions.push({
year: y,
amount: d[y]
})
}
})
dataset.push({
country: d.countryName,
emissions: myEmissions
});
})
console.log(dataset);
//Define x and y domain
xScale
.domain(d3.extent(years, d =>d))
yScale
.domain([d3.max(dataset, d =>
d3.max(d.emissions, d =>
+d.amount)), 0])
//Generate line
let line = d3.line()
.x(d =>
xScale(d.year))
.y(d =>
yScale(d.amount));
let groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")
groups.append("title")
.text(d => d.country)
groups.selectAll("path")
.data(d => [d.emissions])
.enter()
.append("path")
.attr("d", line)
.attr("class", line)
}).catch(error => console.log(error))
Upvotes: 0
Views: 50
Reputation: 5660
Minor change/typo:
You're assigning height
and width
to the body
and not the svg
. Interchanging those 2 lines:
let svg = d3.select("body")
.append("svg")
.attr("width", fullWidth)
.attr("height", fullHeight)
And adding some CSS to the paths:
path.line {
fill: none;
stroke: #000;
}
Here's a fork: https://codepen.io/shashank2104/pen/GwqjVK
Upvotes: 1