Search code examples
cssd3.jssvglinechartarea

In d3, how do I apply a style to my line chart for both the line and the area under the line?


I"m using d3 v4. I want to create a line chart in which I would like to have the area beneath the line filled but I would also like to apply a style to the line itself. I have these classes

.line {
  fill: none;
  stroke: red;
  stroke-width: 1.5px;
}

.area {                         
    fill: url(#area-gradient);                  
    stroke-width: 0px;          
}

but I can't figure out how to apply them to my element. I tried

  svg.append("path")
    .datum(data)
    .attr("d", line)
    .attr("class", "line area")
    .attr("d", area);

but as you can see from this Fiddle -- https://jsfiddle.net/yw46ycse/6/ , the line style doesn't appear (at least I can't see it on Mac Chrome or Firefox).


Solution

  • You are treating your single path like it's two separate elements. It's just one element and your area call (and style) is overriding your line call (and style). If you want to style them different, plot a line and an area.

    svg.append("path")
     .datum(data)
     .attr("class", "area")
     .attr("d", area);
    
    svg.append("path")
     .datum(data)
     .attr("class", "line")
     .attr("d", line);
    

    Updated fiddle.