d3.js绘制柱状图完整代码
时间: 2024-07-30 15:01:00 浏览: 114
D3.js是一个强大的JavaScript库,用于创建数据驱动的文档,包括交互式的可视化。下面是一个简单的D3.js柱状图(bar chart)的完整代码示例,我们将使用HTML、CSS和JavaScript来构建:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3.js Bar Chart</title>
<style>
.bar {
fill: steelblue;
}
text {
font: 12px sans-serif;
}
</style>
</head>
<body>
<svg width="400" height="300"></svg>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
// 假设的数据
const data = [4, 8, 15, 16, 23, 42];
// 设置SVG元素
const svg = d3.select("svg")
.attr("width", "containerWidth")
.attr("height", "containerHeight");
// 宽度和高度
const containerWidth = 400;
const containerHeight = 300;
const barPadding = 5;
const barWidth = (containerWidth / data.length);
// 创建g元素(一组bar)
const bars = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", (d, i) => `translate(${i * barWidth}, 0)`);
// 柱子元素
bars.append("rect")
.attr("class", "bar")
.attr("width", barWidth - barPadding)
.attr("height", d => containerHeight - (d * containerHeight / data.reduce((sum, val) => sum + val, 0)));
// 数据标签
bars.append("text")
.attr("x", barWidth / 2)
.attr("y", containerHeight - 10)
.attr("dy", ".35em")
.text(d => d);
</script>
</body>
</html>
```
在这个例子中,我们首先设置了SVG容器,然后根据数据生成了等宽的柱子,并在每个柱子上添加了数据标签。请注意,你需要根据实际需求调整宽度、高度和其他属性。
阅读全文
相关推荐
















