Skip to content

Instantly share code, notes, and snippets.

@zaslavskij
Last active February 11, 2021 15:06
Show Gist options
  • Select an option

  • Save zaslavskij/a44be26a14f82bd154097d4c8f054e02 to your computer and use it in GitHub Desktop.

Select an option

Save zaslavskij/a44be26a14f82bd154097d4c8f054e02 to your computer and use it in GitHub Desktop.
chart.js
// data example
// [
// {
// "color": "rgb(0, 0, 255)",
// "list": [
// {
// "value": 226454,
// "year": 1970
// },
// {
// "year": 1980,
// "value": 183210
// },
// {
// "year": 1990,
// "value": 219067
// },
// {
// "year": 1991,
// "value": 228811
// }
// ]
// },
// {
// "color": "rgb(255, 36, 0)",
// "list": [
// {
// "value": 81077,
// "year": 1970
// },
// {
// "year": 1980,
// "value": 68966
// },
// {
// "year": 1990,
// "value": 73857
// },
// {
// "year": 1991,
// "value": 77277
// }
// ]
// }
// ]
import React, { useEffect } from "react";
import { line, curveBasis, select } from "d3";
import { scaleLinear } from "d3-scale";
const WIDTH = 600;
const HEIGHT = 400;
const drawChart = (data, Xmin, Xmax, Ymin, Ymax) => {
const scaleX = scaleLinear().domain([Xmin, Xmax]).range([0, WIDTH]);
const scaleY = scaleLinear().domain([Ymin, Ymax]).range([0, HEIGHT]);
const createPath = line()
.curve(curveBasis)
.x((d) => scaleX(d.year))
.y((d) => scaleY(d.value));
const selection = select("#chart").selectAll(".path").data(data);
selection
.enter()
.append("path")
.datum((d) => d.list)
.attr("class", "path")
.attr("fill", "none")
.attr("stroke", (d) => d.color)
.attr("stroke-width", "1")
.attr("d", createPath);
data.forEach((item) => {
selection.datum(item.list).attr("stroke", item.color).attr("d", createPath);
});
selection.exit().remove();
};
const Chart = ({ data, Xmin, Xmax, Ymin, Ymax }) => {
useEffect(() => {
drawChart(data, Xmin, Xmax, Ymin, Ymax);
}, [data]);
return (
<div>
<svg className="bg-white m-4" width={WIDTH} height={HEIGHT} id="chart" />
</div>
);
};
export default Chart;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment