javascript-d3How do I create a horizontal bar chart with D3.js?
Creating a horizontal bar chart with D3.js is relatively simple.
The following example code will create a basic horizontal bar chart with a few hardcoded data points:
<!DOCTYPE html>
<html>
<head>
<title>D3 Horizontal Bar Chart Example</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.bar {
fill: steelblue;
}
</style>
</head>
<body>
<svg width="400" height="200"></svg>
<script>
const svg = d3.select("svg");
const data = [10, 20, 30, 40, 50];
const xScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, 400]);
const yScale = d3.scaleLinear()
.domain([0, data.length])
.range([0, 200]);
const bar = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", (d, i) => yScale(i))
.attr("width", d => xScale(d))
.attr("height", 20)
.attr("class", "bar");
</script>
</body>
</html>
The output of this code will be a horizontal bar chart with 5 bars, each bar representing the corresponding data point:
The code consists of the following sections:
- HTML boilerplate: This includes the
<html>
,<head>
,<title>
, and<style>
tags to set up the page. - Load D3.js: This includes the
<script>
tag to load the D3.js library. - Create SVG element: This includes the
<svg>
tag to create an SVG element to hold the chart. - Set up data: This includes an array of numbers to use as the data points for the chart.
- Create scales: This includes two
scaleLinear()
functions to create an x-scale and a y-scale for the chart. - Create bars: This includes a
selectAll()
andenter()
function to create the bars based on the data and the scales.
For more information on creating bar charts with D3.js, see the following links:
More of Javascript D3
- How can I find a job using d3.js?
- How can I use d3.js to parse XML data?
- How do I use D3.js to zoom on the x-axis?
- How do I create a zoomable chart using d3.js?
- How do I use the z-index property with d3.js?
- How can I display Unix time using d3.js?
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable line chart using d3.js?
- How do I create an x and y axis using d3.js?
- How can I use different types of D3.js in my software development project?
See more codes...