D3.js:根据值更改条的颜色 [英] D3.js: Changing the color of the bar depending on the value
本文介绍了D3.js:根据值更改条的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在试验d3.js条形图,我想改变颜色取决于y轴的值,我该如何实现这一点。我试图添加线性渐变,但后来我失去对它的控制。
I have been experimenting with d3.js bar chart, I want to change the color depending on the value of the y axis, how do I achieve this. I tried adding linear gradients but then I lose control over it.
我正在使用的代码基于此: http://bost.ocks.org/mike/bar/
The code I am working on is based on this: http://bost.ocks.org/mike/bar/
推荐答案
将以下属性添加到适应颜色:
Add the following attributes to adapt the color:
var data = [4, 8, 15, 16, 23, 42];
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) {
return "translate(0," + i * barHeight + ")";
});
bar.append("rect")
.attr("width", x)
// add this attribute to change the color of the rect
.attr("fill", function(d) {
if (d > 25) {
return "red";
} else if (d > 10) {
return "orange";
}
return "yellow";
})
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) {
return x(d) - 3;
})
.attr("y", barHeight / 2)
.attr("dy", ".35em")
// add this attribute to change the color of the text
.attr("fill", function(d) {
if (d > 10) {
return "white";
}
return "black";
})
.text(function(d) {
return d;
});
.chart text {
font: 10px sans-serif;
text-anchor: end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg class="chart"></svg>
这篇关于D3.js:根据值更改条的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文