Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Area Chart with smooth lines possible with D3.js?

I am creating area chart with D3.js and I make it with smooth line. Is it possible?

In my code I just create svg and put line and area on. I use dummy data.

Here is my code below: http://jsfiddle.net/sota0805/mv48H/

// Data
var lineData = [ { "x": 0,    "y": 250},  { "x": 40,   "y": 170},
             { "x": 80,   "y": 140},  { "x": 120,  "y": 220},
             { "x": 160,  "y": 220},  { "x": 200,  "y": 190},
             { "x": 240,  "y": 170},  { "x": 280,  "y": 140},
             { "x": 320,  "y": 200},  { "x": 360,  "y": 180},
             { "x": 400,  "y": 190},  { "x": 440,  "y": 210},
             { "x": 480,  "y": 170},  { "x": 500,  "y": 200},
           ];             

// Drew SVG
var svg = d3.select("body").append("svg")
                       .attr("width", 500)
                       .attr("height", 230);

var area = d3.svg.area()
             .x(function(d)  {  return x(d.x); })
             .y0(230)
             .y1(function(d) {  return y(d.y); });

// Draw line
var lineFunction = d3.svg.line()
           .x(function(d) { return d.x; })
           .y(function(d) { return d.y; })
           .interpolate("basis");                 

var x = d3.scale.linear().range([0, 500]);
var y = d3.scale.linear().range([0, 230]);

x.domain(d3.extent(lineData,  function(d) { return d.x; }));
y.domain([0, d3.max(lineData, function(d) { return d.y; })]);

svg.append("path")
    .attr("class", "area")
    .attr("d", area(lineData));

var linegraph = svg.append("path")
        .attr("d", lineFunction(lineData))
        .attr("stroke", "#549fc2")
        .attr("stroke-width", 0)
        .attr("fill", "none");

Thanks in advance.

like image 378
Sm Yamashita Avatar asked Jun 22 '14 14:06

Sm Yamashita


1 Answers

You have to add the interpolate on the d3.area function, like so:

var area = d3.svg.area()
            .interpolate("monotone")  //Here
            .x(function(d)  {  return x(d.x); })
            .y0(230)
            .y1(function(d) {  return y(d.y); });

More options could be found here: https://www.dashingd3js.com/svg-paths-and-d3js near the end of the page

like image 86
tomtomtom Avatar answered Sep 23 '22 00:09

tomtomtom