I am trying to plot a line using D3, but the line data only appears at the top left corner, could you please help find why the line can not fit into the axis?
var margin = { top: 20, right: 30, bottom: 30, left: 40 },
width = 680 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
var lineData = [{ "x": 1, "y": 5 }, { "x": 20, "y": 20 },
{ "x": 40, "y": 10 }, { "x": 60, "y": 40 },
{ "x": 80, "y": 5 }, { "x": 100, "y": 60 }];
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1)
.domain(lineData.map(function (d) { return d.x; }));
var y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(lineData, function (d) { return d.y; })]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svgContainer = 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 + ")");
var lineFunction = d3.svg.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svgContainer.append("g")
.attr("class", "y axis")
.call(yAxis);
var lineFunction = d3.svg.line()
.x(function (d) { return x(d.x); })
.y(function (d) { return y(d.y); });
You need to apply the scales you created to your line function.
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.