Sriram Sriram - 1 year ago 60
Javascript Question

In multiline chart, at the end of each line i want a small circle and the value of the end point using d3.js

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

body { font: 12px Arial;}

path {
stroke: steelblue;
stroke-width: 2;
fill: none;

.axis path,
.axis line {
fill: none;
stroke: green;
stroke-width: 1;
shape-rendering: crispEdges;


<script src="d3.min.js"></script>

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - - margin.bottom;

var parseDate = d3.time.format("%Y-%m-%d").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)

var yAxis = d3.svg.axis().scale(y)

// Define the line
var priceline = d3.svg.line().interpolate("basis")
.x(function(d) { console.log(d.T1); return x(d.T1); })
.y(function(d) { return y(d.NATURE_QUERY); });

// Adds the svg canvas
var svg ="body")
.attr("width", width + margin.left + margin.right)
.attr("height", height + + margin.bottom)
"translate(" + margin.left + "," + + ")");

// Get the data
d3.csv("datatest.csv", function(error, data) {
data.forEach(function(d) {
d.T1 = parseDate(d.T1);
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.T1; }));
y.domain([0, d3.max(data, function(d) { return d.NATURE_QUERY; })]);

// Nest the entries by symbol
var dataNest = d3.nest()
.key(function(d) {return d.CLOSING_DEPT;})

// Loop through each symbol / key
dataNest.forEach(function(d) {
.attr("class", "line")
.attr("d", priceline(d.values));


// Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")

// Add the Y Axis
.attr("class", "y axis")



This is my code but i want to draw a small circle at the end of each line along with the value of the end point.I dint add my data file here, and am new to d3.js so do suggest me with the ideas. Thank you

Please find the tsv dataset here

Answer Source

You can do it like this:

        //iterate over all the data for line to get the last point of a line.
        var k = d.values
        var last = k[k.length -1];//get the last value of the line
        .attr("cx", function(d){return x(last.T1);})//make a circle at the last point
        .attr("cy", function(d){return y(last.NATURE_QUERY);})
        .attr("r", 4);
        //make a text 
        .attr("x", function(){return x(last.T1) + 20;})
        .attr("y", function(){return y(last.NATURE_QUERY);})
        .text(function(){return last.CLOSING_DEPT;})  //set the text you want to display.      

working code here