I remember being able to do this quite easily in v3, but I've decided to give v4 a go recently after a bit of a hiatus and of course a lot has seemed to change, syntax wise at least.
So I thought I would start off with this example , without using a time scale for the x axis.
I've been trying to refer to the d3 scale api docs , but after trying out various things ( ordinalScale()
& scaleBand()
mainly) I can only seem to get the first and last items to appear on the x axis.
When generating the line, it also appears to be playing up a bit.
Here is my code;
let tData = [{x: 1, y: 5}, {x: 2, y: 10}, {x: 3, y: 15}, {x: 4, y: 20}, {x: 5, y: 25}, {x: 6, y: 30}, {x: 7, y: 35}, {x: 8, y: 40}]
let svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let y = d3.scaleLinear().rangeRound([height, 0]);
let x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
let line = d3.line()
.x((d) => x(d.x))
.y((d) => y(d.y))
x.domain(d3.extent(tData, ((d) => d.x)));
y.domain(d3.extent(tData, ((d) => d.y)));
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.select(".domain")
.remove();
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Price ($)");
g.append("path")
.datum(tData)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
and a Plunk to go with it;
http://plnkr.co/edit/EJqsjhaGNZ8u3PkEgy2l?p=preview
Hope someone can point me in the right direction?
Thanks!
Because the x axis is a scaleBand, it needs to know about all possible domain "buckets". In this example of using strings for domain , all values are identified as the domain values; not just the min and max.
In your code you use:
x.domain(d3.extent(tData, ((d) => d.x)));
to identify the min and max of the domain.
Instead, try identifying all possible values, using:
x.domain(tData.map( function(d) { return d.x; } ));
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.