Reputation: 69
I want to add labels that show the values on a line chart and can't figure out how to do this.
var svg = d3.select('svg')
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.attr("transform", "translate(" + 0 + "," + 0 + ")");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.date)})
.y(function(d) { return y(d.value)})
x.domain(d3.extent(data, function(d) { return d.date }));
y.domain(d3.extent(data, function(d) { return d.value }));
I don't know how to add labels, like here for example (though my case is simpler, because I have only one chart)
Upvotes: 1
Views: 380
Reputation: 5660
I've generated some random data here. Relevant code to add the text labels:
g.selectAll('.textLabels')
.data(data).enter()
.append('text')
.classed('textLabels', true)
.attr('x', function(d) { return x(d.date); })
.attr('y', function(d) { return y(d.value); })
.text(function(d) { return d.value; });
which are positioned based on x
(date) and y
(value) values in the data array. You can adjust the offsets using dx
, dy
attributes and use some styles to fill/stroke
the text.
var data = [];
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
for(var i=0; i<20; i++) {
var obj = {};
obj.date = randomDate(new Date(2018, 01,01), new Date());
obj.value = Math.floor(Math.random() * 50);
data.push(obj);
}
data.sort(function(a, b) {
return a.date > b.date ? -1 : 1;
})
var width = 800, height = 400;
var svg = d3.select('svg')
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.attr("transform", "translate(" + 0 + "," + 0 + ")");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) {
return x(d.date)
})
.y(function(d) {
return y(d.value)
})
x.domain(d3.extent(data, function(d) {
return d.date
}));
y.domain(d3.extent(data, function(d) {
return d.value
}));
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
g.selectAll('.textLabels')
.data(data).enter()
.append('text')
.classed('textLabels', true)
.attr('x', function(d) { return x(d.date); })
.attr('y', function(d) { return y(d.value); })
.text(function(d) { return d.value; });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Let me know if you have any questions. Hope this helps.:)
Upvotes: 2