I am new creating charts with d3 and Im trying to build a line chart with ordinal axis. I have managed to visualize the y axis and the x axis correctly, but I am not able to create the line.
I have this code:
var margin = {top: 10, right: 30, bottom: 30, left: 60},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var data = [{
name: "cat",
value: 10
}, {
name: "dog",
value: 3
}, {
name: "pig",
value: 7
}, {
name: "bird",
value: 7
}];
//append the svg object to the body of the page
var svg = d3.select("#div-svg" ).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 + ")");
//set scale
var xScale = d3.scaleBand()
.domain(d3.extent(data, function(d){return d["name"]}))
.range([0, width]),
yScale = d3.scaleLinear()
.domain([min(this.value_array), max(this.value_array)])
.range([height, 0]);
//add Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
Up to here everything works fine. The next part is the onethat doesn't work.
//line
var line = d3.line()
.x(function(d) { return xScale(d[0]); })
.y(function(d) { return yScale(d.value); })
If I put d[0] I get the following error " type number is not assignable to parameter of tye string ". If I put d.name I get the following error " 'name' does not exist on type [number,number] ". I don't know how to proceed to display the chart. Do you have any solution?
Also I would like it to be an area chart not just a linechart, in case the procedure changes.
d3.extent
is not what you want to use for the domain. You need an array with each of the bar names.
var xScale = d3.scaleBand()
.domain(data.map(function(d){return d["name"]}))
.range([0, width])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.