JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<script src="https://d3js.org/d3.v7.min.js"></script>

<div id='line-chart'>
</div>

JavaScript

// Select the SVG container
const svg = d3.select("#line-chart")
  .append("svg")
  .attr("width", 500)  // Width of the SVG
  .attr("height", 300); // Height of the SVG

// Define margins and dimensions for the chart
const margin = { top: 20, right: 30, bottom: 30, left: 40 };
const width = 500 - margin.left - margin.right;
const height = 300 - margin.top - margin.bottom;

// Create a group element for the chart and translate it downwards by the height
const chart = svg.append("g")
  .attr("transform", `translate(${margin.left}, ${margin.top + height})`);

// Generate random data points
const data = Array.from({ length: 10 }, () => Math.floor(Math.random() * 100));

// Define scales for x and y axes
const xScale = d3.scaleLinear()
  .domain([0, data.length - 1]) // Input domain (data indices)
  .range([0, width]); // Output range (width of the chart)

const yScale = d3.scaleLinear()
  .domain([0, d3.max(data)]) // Input domain (data values)
  .range([0, -height]); // Output range (height of the chart, but negative)

// Define x and y axes
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);

// Draw x axis
chart.append("g")
  .attr("transform", `translate(0, 0)`)
  .call(xAxis);

// Draw y axis
chart.append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(yAxis);

// Define the line function
const line = d3.line()
  .x((d, i) => xScale(i)) // x-coordinate based on the index of the data point
  .y(d => yScale(d))      // y-coordinate based on the data value

// Draw y axis
const yAxisGroup = chart.append("g")
  .attr("transform", `translate(0, 0)`) // Adjust the y translation here
  .call(yAxis);

// Draw the line chart
chart.append("path")
  .datum(data)             // Binds data to the line
  .attr("fill", "none")    // No fill color
  .attr("stroke", "steelblue") // Line color
  .attr("stroke-width", 2) // Line width
  .attr("d", line);        // Path data generated by the line function