javascript-d3How do I use D3.js to create examples?
D3.js is a powerful JavaScript library used to create data-driven documents. It allows developers to create interactive data visualizations in the browser. Here is an example of how to use D3.js to create a simple bar chart:
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script>
var data = [4, 8, 15, 16, 23, 42];
var x = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, 420]);
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; });
</script>
</body>
</html>
This code will create a simple bar chart with 6 bars, each bar representing a value in the data
array.
The code can be broken down into the following parts:
- Include the D3 library in the HTML head:
<script src="https://d3js.org/d3.v5.min.js"></script>
- Create the
data
array:
var data = [4, 8, 15, 16, 23, 42];
- Create a linear scale to map the data values to the width of the bars:
var x = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, 420]);
- Select the HTML element to contain the chart and bind the
data
array to it:
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
- Append a
div
element for each data value and set the width of eachdiv
to the mapped value:
.append("div")
.style("width", function(d) { return x(d) + "px"; })
- Add the data value as text to each
div
:
.text(function(d) { return d; });
For more information on using D3.js, see the official documentation.
More of Javascript D3
- How can I use d3.js to create a zoom scale?
- How do I use d3.js to zoom to a selected area?
- How do I set up the x axis in d3.js?
- How can I use d3.js with Next.js?
- How do I use d3.js to enable zooming and panning in my web application?
- How can I use d3.js xscale to create a chart?
- How do I install and use D3.js with Yarn?
- How can I use d3.js to parse XML data?
- How can I use d3.js to create interactive data visualizations?
- How can I create a time scale on the x-axis using d3.js?
See more codes...