JSFiddle - React, Tailwind, and code Playground

by grindlemire

HTML

<!DOCTYPE html>
<html lang='en'>
  <head>
    <script src='https://d3js.org/d3.v6.min.js'></script>
  </head>
  <body>
  <div id='test'></div>
  </body>
</html>

JavaScript

const data = [{
    group: "CA",
    year: 1993,
    males: 100,
    females: 95,
    pets: 12
  },
  {
    group: "CA",
    year: 1994,
    males: 80,
    females: 88,
    pets: 8
  },
  {
    group: "CA",
    year: 1995,
    males: 70,
    females: 30,
    pets: 34
  },
  {
    group: "TX",
    year: 1996,
    males: 111,
    females: 122,
    pets: 32
  },
  {
    group: "TX",
    year: 1997,
    males: 25,
    females: 25,
    pets: 64
  },
  {
    group: "HI",
    year: 1998,
    males: 13,
    females: 45,
    pets: 72
  },
]

const keys = ["males", "females", "pets"];
const colors = {
  males: "blue",
  females: "pink",
  pets: "green",
  TX: "red",
  HI: "purple",
  CA: "yellow"
};

// Width and height of our original box
const width = 1000;
const height = 1000;
// Margin we want, and making the center SVG to hold our graph
const margin = {
  top: 80,
  right: 180,
  bottom: 80,
  left: 180
};
const padding = 0.1;

const dataByState = d3.group(data, d => d.group)
const dataByYear = d3.group(data, d => d.year)

// Creating a function to create layers
const stackGenerator = d3.stack().keys(keys); // now a function
// Creating layers from our data and keys
// keys = our layers
const layers = stackGenerator(data); // now a function


// Origin of an SVG is in the TOP LEFT corner
const svg = d3
  .select("#test")
  .append("svg") // append an svg element to our div#test
  // Creating the actual height and width of our svg to hold report
  .attr("height", height - margin.top - margin.bottom)
  .attr("width", width - margin.left - margin.right)
  .attr("viewBox", [0, 0, width, height])
  .style("background-color", "white")


// Create an outer axis that we will use to group initially
const outerGroupXScale = d3.scaleBand().domain(dataByState.keys()).range([margin.left, width - margin.right]).padding(0.05)
const outerGroupXAxis = g => {
  // bottom align it
  g.attr("transform", `translate(0, ${height - margin.bottom/2})`)
    .attr("class", "x-axis")
   ...