Files

50 lines
1.7 KiB
HTML
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>d3</title>
<script src="http://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
// 定义SVG画布的宽度和高度
var width = 600;
var height = 600;
// 创建SVG画布并将其添加到body中设置画布的宽度和高度
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
// 定义数据集,每个数值表示一个矩形条的长度比例
var dataset = [30,20,35,32,21];
// 定义颜色比例尺,将数据值映射到颜色
var colorScale = d3.scaleLinear()
.domain([d3.min(dataset), d3.max(dataset)]) // 数据值范围
.range(["blue", "red"]); // 颜色范围
// 绑定数据到SVG中的rect元素并根据数据生成矩形条
svg.selectAll("rect")
.data(dataset) // 绑定数据集到rect元素
.enter() // 为数据集中每个元素创建一个新的rect元素
.append("rect") // 添加rect元素到SVG中
.attr("x",10) // 设置矩形条的起始x坐标
.attr("y",function(d,i){
// 根据索引计算每个矩形条的y坐标确保它们垂直排列
return i * 30;
})
.attr("width",function(d,i){
// 根据数据值动态设置矩形条的宽度
return d * 10;
})
.attr("height",28) // 设置矩形条的高度
.attr("fill", function(d) {
// 根据数据值动态设置填充颜色
return colorScale(d);
});
</script>
</body>
</html>