reactjsd3.js

How to change the appearance of D3 chart in react?


I have worked through the following tutorial to create a D3 chart using react:

https://paulho1973.medium.com/create-line-chart-with-d3-and-react-a0ae9a5e1f7

I know how to change the colour of the line but how do I amend the code so that the chart background is black and the line is white?

At the moment the background is white and the line is black.

import React, { useEffect } from "react";
import * as d3 from "d3";

function App() {

  const createGraph = async () => {

    // read data from csv and format variables
    let data = await d3.csv('https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv')
    var parseTime = d3.timeParse("%Y-%m-%d");
  
    data.forEach((d) => {
      d.date = parseTime(d.date);
      d.value = +d.value;
    });
    console.log(data)

    // set the dimensions and margins of the graph
    var margin = { top: 20, right: 20, bottom: 50, left: 70 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`);

    // add X axis and Y axis
    var x = d3.scaleTime().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    x.domain(d3.extent(data, (d) => { return d.date; }));
    y.domain([0, d3.max(data, (d) => { return d.value; })]);
  
    svg.append("g")
      .attr("transform", `translate(0, ${height})`)
      .call(d3.axisBottom(x));

    svg.append("g")
      .call(d3.axisLeft(y));
      
    // add the Line
    var valueLine = d3.line()
    .x((d) => { return x(d.date); })
    .y((d) => { return y(d.value); });
  
    svg.append("path")
      .data([data])
      .attr("class", "line")
      .attr("fill", "none")
      .attr("stroke", "black")
      .attr("stroke-width", 2)
      .attr("d", valueLine);

  }

  useEffect(() => {
    createGraph();
  }, []);

  return (
    <>

    </>
  );
}

export default App

Solution

  • To change the background of your D3 chart to black and the line to white, I recommend to set the SVG background color to black and change the line color to white:

    .style("background-color", "black")
    
    .attr("stroke", "white")
    
    .selectAll("text").style("fill", "white")