Home > Blockchain >  Give different colors to area under and over a specific point on a D3 line chart
Give different colors to area under and over a specific point on a D3 line chart

Time:12-20

I've recently started working with D3 and I am moving all my existing charts over from Chartjs and so far my attempts have been successful. There is this one chart however that I am unable to produce exactly the same way in D3.

So with Chartjs, there's properties built in to the library that we can use to set the colors for values above and below a certain point on a Line chart. Here's what I had used to get the intended chart with Chartjs:

...config,
fill: {
  above: '#4E4AFF20',
  below: '#FF515114',
  target: 'origin'
},
...config

And this is what the chart in Chartjs ended up looking like:

enter image description here

But D3 doesn't seem to have such a thing as far as I can tell. There's only gradients. So here's what I was able to build in D3:

enter image description here

As you can see, this looks way different from what I had earlier with Chartjs. Also notice how the gradient exists in both the line and the colored area underneath. I know it's there because I added it but that's not what I want and everywhere I look, that's the only way people are doing it. I have done countless attempts to fix this to no avail hence now I'm here asking for your help. Here's the D3 code I have right now:

import * as d3 from 'd3';
import { useEffect, useRef } from 'react';

interface Data {
  x: number;
  y: number;
}

const width = 350;
const height = 117;
const zeroPoint = 0;
const data: Data[] = [
  { x: 0, y: -20 },
  { x: 10, y: -20 },
  { x: 20, y: -20 },
  { x: 40, y: -20 },
  { x: 50, y: -20 },
  { x: 60, y: -20 },
  { x: 70, y: -20 },
  { x: 80, y: 0 },
  { x: 90, y: 20 },
  { x: 100, y: 20 },
  { x: 110, y: 20 },
  { x: 120, y: 20 },
  { x: 130, y: 20 },
  { x: 140, y: 20 },
  { x: 150, y: 20 }
];

export const Chart: React.FC = () => {
  const ref = useRef<SVGSVGElement>(null);

  const generateLinePath = (
    element: d3.Selection<SVGSVGElement, unknown, null, undefined>,
    data: Data[],
    xScale: d3.ScaleLinear<number, number>,
    yScale: d3.ScaleLinear<number, number>
  ) => {
    const lineGenerator = d3
      .line<Data>()
      .x(d => xScale(d.x))
      .y(d => yScale(d.y));
    element.append('path').attr('d', lineGenerator(data));
  };

  const drawZeroLine = (element: d3.Selection<SVGSVGElement, unknown, null, undefined>, yScale: d3.ScaleLinear<number, number>) => {
    element
      .append('line')
      .attr('x1', '0')
      .attr('y1', yScale(zeroPoint))
      .attr('x2', width)
      .attr('y2', yScale(zeroPoint))
      .attr('stroke', '#c4c4c4');
  };

  const createChart = (data: Data[]) => {
    const svg = d3.select(ref.current!).attr('viewBox', `0 0 ${width} ${height}`);

    svg.selectAll('*').remove();

    const [minX, maxX] = d3.extent(data, d => d.x);
    const [minY, maxY] = d3.extent(data, d => d.y);

    const xScale = d3.scaleLinear().domain([minX!, maxX!]).range([0, width]);
    const yScale = d3
      .scaleLinear()
      .domain([minY!, maxY!])
      .range([height, 0]);

    svg
      .append('linearGradient')
      .attr('id', 'line-gradient')
      .attr('gradientUnits', 'userSpaceOnUse')
      .attr('x1', 0)
      .attr('x2', width)
      .selectAll('stop')
      .data(data)
      .join('stop')
      .attr('offset', d => xScale(d.x) / width)
      .attr('stop-color', d => (d.y < zeroPoint ? '#FF5151' : '#4E4AFF'));

    svg
      .append('linearGradient')
      .attr('id', 'area-gradient')
      .attr('gradientUnits', 'userSpaceOnUse')
      .attr('x1', xScale(data[0].x))
      .attr('x2', xScale(data[data.length - 1].x))
      .selectAll('stop')
      .data([
        { color: '#FF515110', offset: '0%' },
        { color: '#4E4AFF20', offset: '100%' }
      ])
      .enter()
      .append('stop')
      .attr('offset', function (d) {
        return d.offset;
      })
      .attr('stop-color', function (d) {
        return d.color;
      });

    svg.attr('stroke', 'url(#line-gradient)').attr('fill', 'url(#area-gradient)');

    generateLinePath(svg, data, xScale, yScale);
    drawZeroLine(svg, yScale);
  };

  useEffect(() => {
    createChart(data);
  }, []);

  return <svg ref={ref} />;
};

So there's two problems I am looking to get solved with your help. The more important one is to give different colors to areas under and above the zero line in D3 the way I was able to do with Chartjs and the other one is moving away from gradients and get solid colors without any smooth transitions on both the line and the colored areas underneath.

CodePudding user response:

Alright I managed to recreate the same chart in D3 using a workaround.

enter image description here

So it's not as straightforward as it's in Chartjs but it works pretty well. The idea is to create polygons under and over the line using the same data used to generate the line.

So my chart works like this. The grey line is a straight zero line and the values below zero go under that line with a red color and the ones above are purple. And here's what the Chart data looks like:

data = [
  { x: 0, y: 0 },
  { x: 1, y: 1 },
  ...
]

Anyways, here's the steps

  1. Generate the scales
const [minX, maxX] = d3.extent(data, d => d.x);
const [minY, maxY] = d3.extent(data, d => d.y);

const xScale = d3.scaleLinear().domain([minX, maxX]).range([0, width]);
const yScale = d3.scaleLinear().domain([minY, maxY]).range([height, 0]);
  1. Generate the line chart using D3's line() function. And don't give any stroke to the generated line.
const lineGenerator = d3.line().x(d => xScale(d.x)).y(d => yScale(d.y));
element.append('path').attr('d', lineGenerator(data));
  1. Add a red SVG polygon that starts from the left side at zero line, then goes to the left bottom, then to where the value starts becoming negative and then finally to where the line reaches the zero line again.
svg.append('polygon').attr(
  'points',
  `
   ${xScale(minX - 1)},${yScale(0)} // top left point
   ${xScale(minX - 1)},${yScale(minY)} // bottom left point
   ${xScale(data[indexWhereRedPointStartsBecomingPositive].x)},${yScale(data[indexWhereRedPointStartsBecomingPositive].y)} // bottom right point
   ${xScale(data[indexWhereXReachesZeroLine].x)},${yScale(0)} // top right point
  `
)
.attr('fill', 'lightRed')
.attr('stroke', 'darkRed');

enter image description here

Notice how we gave the red stroke to the polygon? That's the reason why we got rid of the stroke from the line and gave it here instead. This is because we need two separate colors (red for below and purple for above) for the chart. The reason why we do minX - 1 is because the stroke is applied to all four sides of the polygon and we want to hide it from the left side so we subtract 1px from the left.

  1. Add another purple SVG polygon that starts from the left side at zero line (where the purple area starts somewhere in the middle), then goes all the way to the right end of the chart and then goes up to the top.
svg.append('polygon').attr(
  'points',
  `
    ${xScale(data[indexWhereValueStartsGoingPositive].x)},${yScale(0)}
    ${width   1},${yScale(data[data.length - 1].y)}
    ${width   1},${yScale(0)}
  `
)
.attr('fill', 'lightPurple')
.attr('stroke', 'darkPurple');

Here we do width 1 to hide the stroke of this purple polygon on the right side the same way we did minX - 1 with the left side of the red box.

enter image description here

So in conclusion, instead of giving stroke to the line generated using d3.line(), give strokes to the two polygons created using the same data that was used to generate the line chart and create the polygons 1px larger than the chart data so the strokes don't appear on the left and right side of the charts.

That's quite a lot I know but I couldn't think of any other way to get the chart to look like this. Anyways, I hope this helps anyone else experiencing a similar problem.

  • Related