D3绘制简单条形统计图
效果图:
(图中箭头出表示鼠标位置,交互显示位置处的矩形)
完整代码:
<body>
<script src="https://d3js.org/d3.v5.js"></script>
<script>
let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
w *= 0.98;
h *= 0.9;
let svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
let a = new Array(10);
for (let i = 0; i < 10; ++i)
a[i] = Math.random() * 200;
svg.selectAll("rect")
.data(a)
.enter()
.append("rect")
.attr("x", function (d, i) {
return i * (w / a.length);
})
.attr("y", function (d) {
return h - d;
})
.attr("width", (w / a.length - 10))
.attr("height", function (d) {
return d;
})
.attr("fill", function (d, i) {
return 'rgba(0,' + (200 - d) + ',0,0.8)';
})
.on("mouseover", function (d) {
d3.select(this)
.attr("fill", 'blue');
})
.on("mouseout", function (d) {
d3.select(this)
.attr("fill", 'rgba(0,' + (200 - d) + ',0,0.8)');
});
</script>
</body>
代码解释:
rect元素:d3在svg中绘制矩形的元素
.attr() 设置属性
.attr("x", function (d, i) {
return i * (w / a.length);
})
.attr("y", function (d) {
return h - d;
})
分别设置每个矩形左上点坐标(x,y)的x值和y值。
要注意选中的画布的左上角坐标是(0,0),为了使矩形画到画面的下方,y值不能直接引用d的值。
.attr("width", (w / a.length - 10))
.attr("height", function (d) {
return d;
})
设置每个矩形的宽和长。
.attr("fill", function (d, i) {
return 'rgba(0,' + (200 - d) + ',0,0.8)';
})
填充每个矩形的颜色。
rgba即是 Red + Green + Blue + Alpha。红色值 + 绿色值 + 蓝色值 + 透明度。前三项的值取值范围是0 ~ 255(十六进制0xFF)。透明度取值0 ~ 1。
注意出现变量时的格式。
.on("mouseover", function (d) {
d3.select(this)
.attr("fill", 'blue');
})
.on("mouseout", function (d) {
d3.select(this)
.attr("fill", 'rgba(0,' + (200 - d) + ',0,0.8)');
})
交互部分,设置该矩形在移入鼠标时的行为和移出后的行为。