React Data Visualization — Adding Fill to a Line Chart

Brandon Morelli
Jul 20, 2017 · 2 min read

Edit: Kris got me intrigued. Just released a walk-through on how to build a clone of Coinbase.com’s Bitcoin charts. Article is here.

Hey Kris, it’s actually a pretty easy fix. The reason editing the fill doesn’t work is because linechart_path isn’t actually a shape — it’s just a line.

So in order to get an area chart, we need to create a new path that is actually a shape — then we’ll be able to add fill and get the desired result.

Here’s a codepen showing the desired result:

We can add a new function named makeArea(). makeArea() will start out looking exactly the same as makePath():

makeArea() {
const {data} = this.props;
let pathD =
"M " + this.getSvgX(data[0].x) + " " + this.getSvgY(data[0].y) + " ";
data.map((point, i) => {
pathD += "L " + this.getSvgX(point.x) + " " + this.getSvgY(point.y) + " ";
});

Above, we create a pathD variable and use our data to create a line chart. So far the same. Now however, we’re going to append to our pathD variable to make it a shape:

pathD += "L " + this.getSvgX(this.getMaxX()) + " " + this.getSvgY(this.getMinY()) + " "
+ "L " + this.getSvgX(this.getMinX()) + " " + this.getSvgY(this.getMinY()) + " ";
return <path className="linechart_area" d={pathD} />
}

We move from the last data point, to the bottom right of our chart, then to the bottom left of our chart! Now, when we add a fill color, it will work as expected.

Only thing left to do is return {this.makeArea()} and add some styles to our css:

.linechart_area {
fill: #2ecc71;
stroke: none;
opacity: .4;
}

Hope this helps!

)

Brandon Morelli

Written by

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade