Here is the data file named: myStData.csv
xindex,mylabel
40,23
41,13
42,12
43,21
44,40
45,50
In this code snippet, the label is currently shown at the "start" position (text-anchor set to start). The label is placed according to the start value in the csv file. However, I need the label to be positioned at the end value instead. I attempted to change the start text anchor to end, but it didn't work as expected. Any assistance regarding this matter would be highly appreciated.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.10/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body { font: 13px Helvetica;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
.legend {
font-size: 16px;
text-anchor: start;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 30, right: 40, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
//var x = d3.time.scale().range([0, width]);
var x = d3.scale.linear().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(14);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function(d) { return x(d.xindex); })
.y(function(d) { return y(d.mylabel); });
var chart1 = d3.select("body")
.append("svg")
.attr("width", width + margin.left + (margin.right * 2))
.attr("height", height + margin.top + (margin.bottom * 2))
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.csv("myStData.csv", function(error, data) {
data.forEach(function(d) {
d.xindex = +d.xindex;
d.mylabel = +d.mylabel;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.xindex; }));
y.domain([0, d3.max(data, function(d) { return d.mylabel; })]);
chart1.append("path")// Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data));
chart1.append("g")// Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart1.append("g")// Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
chart1.append("text")
.attr("transform", "translate(" + (width+3) + "," + y(data[0].mylabel) + ")")
.attr("dy", ".35em")
.attr("class","legend")
.attr("text-anchor", "end")
.style("fill", "red")
.text("MyLabel");
// Add the text label for the Y axis
chart1.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Y-Axis Label");
// Add the text label for the x axis
chart1.append("text")
.attr("transform", "translate(" + (width / 2) + " ," + (height + (margin.bottom * 1.5)) + ")")
.style("text-anchor", "middle")
.text("X-Axis Label");
});