D3.js:根据值更改条形的颜色

时间:2016-01-27 13:20:38

标签: javascript d3.js

我一直在试验d3.js条形图,我想根据y轴的值改变颜色,我该如何实现。我尝试添加线性渐变,但后来我失去了对它的控制。

我正在处理的代码基于:http://bost.ocks.org/mike/bar/

2 个答案:

答案 0 :(得分:7)

添加以下属性以调整颜色:



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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您必须使用分位数刻度来调整颜色范围。您可以在此处获取文档https://github.com/mbostock/d3/wiki/Quantitative-Scales

您也可以参考http://colorbrewer2.org/了解颜色范围。

&#13;
&#13;
var data = [4, 8, 15, 16, 23, 42];

var colors = ["#ffffd9", "#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#1d91c0", "#225ea8", "#253494", "#081d58"];

var colorScale = d3.scale.quantile()
  .domain([0, colors.length - 1, d3.max(data, function(d) {
    return d;
  })])
  .range(colors);


var x = d3.scale.linear()
  .domain([0, d3.max(data)])
  .range([0, 420]);

d3.select(".chart")
  .selectAll("div")
  .data(data)
  .enter().append("div")
  .style("width", function(d) {
    return x(d) + "px";
  })
  .style("background-color", function(d) {
    return colorScale(d);
  })
  .text(function(d) {
    return d;
  });
&#13;
.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div class="chart"></div>
&#13;
&#13;
&#13;