gpt4 book ai didi

javascript - 如何为不同的百分比渲染不同颜色的 d3.arc?

转载 作者:行者123 更新时间:2023-11-30 20:46:02 25 4
gpt4 key购买 nike

我正在使用 d3.arc 来渲染径向组件。代码是:

https://codepen.io/zhaoyi0113/pen/PEgYZX

当前代码渲染了一个带百分比的圆弧,颜色为红色。请看下面的截图:

enter image description here

我想为不同的百分比设置颜色。例如,从 0% 到 20% 显示绿色,从 20% 到 50% 显示橙色,50% 以上显示红色。如何在 d3 上进行此更改?

还有一件事我需要提一下,我想在径向分量中显示所有相关的颜色。例如,前 20% 是绿色,20% 到 50% 显示橙色,50% 以上显示红色。

最佳答案

您所描述的只是带有自定义颜色的传统圆环图:

<!DOCTYPE html>
<html>

<head>
<script src="//d3js.org/d3.v4.min.js"></script>
</head>

<body>
<svg width="960" height="500"></svg>
<script>
var tau = 2 * Math.PI; // http://tauday.com/tau-manifesto

// An arc function with all values bound except the endAngle. So, to compute an
// SVG path string for a given angle, we pass an object with an endAngle
// property to the `arc` function, and it will return the corresponding string.
var arc = d3.arc()
.innerRadius(80)
.outerRadius(100)
.cornerRadius(20);

var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

// Add the background arc, from 0 to 100% (tau).
var background = g.append("path")
.datum({
endAngle: tau
})
.style("fill", "#ddd")
.attr("d", arc);

var data = [.2, .3, .51];
var c = d3.scaleThreshold()
.domain([.201, .501, 1])
.range(["green", "orange", "red"]);

var pie = d3.pie()
.sort(null)
.value(function(d) {
return d;
});

g.selectAll(".arc")
.data(pie(data))
.enter()
.append("path")
.attr("class", "arc")
.style("fill", function(d) {
return c(d.value);
})
.attr("d", arc);
</script>
</body>

</html>

关于javascript - 如何为不同的百分比渲染不同颜色的 d3.arc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com