@elisha_langworth
To create a bar chart using d3.js, you need to follow these steps:
Here is an example code snippet to create a bar chart using d3.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html> <head> <script src="https://d3js.org/d3.v6.min.js"></script> </head> <body> <div id="chart"></div> <script> // Define the data var data = [ { label: "A", value: 10 }, { label: "B", value: 20 }, { label: "C", value: 15 }, { label: "D", value: 25 }, { label: "E", value: 12 } ]; // Set up the SVG container var svg = d3.select("#chart") .append("svg") .attr("width", 400) .attr("height", 300); // Define the scales var xScale = d3.scaleBand() .domain(data.map(d => d.label)) .range([0, 300]) .padding(0.1); var yScale = d3.scaleLinear() .domain([0, d3.max(data, d => d.value)]) .range([0, 200]); // Add the bars svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("x", d => xScale(d.label)) .attr("y", d => 300 - yScale(d.value)) .attr("width", xScale.bandwidth()) .attr("height", d => yScale(d.value)) .attr("fill", "steelblue"); // Add the axes svg.append("g") .attr("transform", "translate(0, 300)") .call(d3.axisBottom(xScale)); svg.append("g") .call(d3.axisLeft(yScale)); // Style the chart svg.selectAll("text") .attr("font-family", "sans-serif") .attr("font-size", "12px") .attr("fill", "white"); </script> </body> </html> |
This code will create a bar chart with five bars representing the data points provided. You can customize the chart further by modifying the data, scales, styles, and other attributes as needed.