【问题标题】:dc.js making a color range between two coloursdc.js 在两种颜色之间创建一个颜色范围
【发布时间】:2017-05-04 18:36:25
【问题描述】:

我让用户从下拉列表中选择四个数字系列之一,以驱动气泡图中的圆圈着色。 (半径、x 和 y 也有类似的下拉菜单。)

d3.select("select#colour").on('change',function(d) {
  var tempIndex = this.selectedIndex;
  yearlyBubbleChart.colorAccessor(function (p) {
    return p.value[optionArray[0][tempIndex]];
  });
  yearlyBubbleChart.colors(colorbrewer[optionArray[7][tempIndex]][optionArray[8][tempIndex]]);
  yearlyBubbleChart.colorDomain([optionArray[5][tempIndex][0], optionArray[5][tempIndex][1]]);
});

为此,我按顺序使用 colorAccessor、colors 和 colorDomain。 (我注意到在某些情况下这三个的顺序很重要。)我希望用户能够选择最小和最大颜色,并从中驱动颜色。为此,我需要用两种颜色为气泡着色,例如['白色','蓝色']。数值越高,相应地越蓝。

这似乎是一件很容易做到的事情,但我无法解决。提供两种颜色的数组通常用于交替,在气泡图中,最小的气泡是白色的,其余的是蓝色的。如何通过仅输入两种颜色来获得连续的颜色范围?

谢谢

【问题讨论】:

  • 这里的关键是colorMixin.colors()可以采用任何类型的d3比例。如果你向它传递一个颜色数组,它会为你创建一个ordinal scale,但你可以使用如下@Paul 所示的线性比例,或者如果你将一个连续域映射到一组离散的颜色。
  • 是的,如果你look at the source for the color mixin,你就会明白为什么你需要在colorDomain 之前调用colors——前者替换了刻度,后者在当前刻度上设置了一个参数。

标签: javascript d3.js colors dc.js crossfilter


【解决方案1】:

d3 知道如何在颜色之间进行插值。您可以创建范围(输出值)为颜色的线性刻度。

var colorScale = d3.scale.linear()
  .domain([0, 1])
  .range(['white', 'blue'])

下面是一个示例,它显示了比例尺以设定的百分比生成的各种颜色(其中 0% 是全白,100% 是全蓝)。

var ele = d3.select('#holder');

var width = 500;
var height = 25;
var margin = 30;

// these are the values in the domain 0 to 1 for which
// we will draw bands (whose color is somewhere between
// white and blue).
var percents = [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1];

// a continuous scale from 'white' to 'blue'
var colorScale = d3.scale.linear()
  .domain([0, 1])
  .range(['white', 'blue'])

var x = d3.scale.ordinal()
  .domain(percents)
  .rangeBands([0, width]);

var g = ele.append('svg')
  .attr('width', width + 2*margin)
  .attr('height', height + 2*margin)
  .append('g')
  .attr('transform', 'translate(' + margin + ',' + margin + ')');

// axis
var axis = d3.svg.axis()
  .orient('bottom')
  .scale(x)
  .tickFormat(d3.format('.2f'))

g.append('g')
  .classed('x axis', true)
  .call(axis);

var values = g.append('g')
  .classed('percents', true)
  .selectAll('g.percent')
  .data(percents)
  .enter().append('g')
  .classed('percent', true)
  .attr('transform', function(d){
    return 'translate(' + x(d) + ',-10)';
  });

var bandwidth = x.rangeBand();
values.append('rect')
  .attr('x', 0)
  .attr('width', bandwidth)
  .attr('y', -25)
  .attr('height', 25)
  // use the colorScale to determine the color of each band
  .style('fill', colorScale);
.domain, .tick line {
  fill: none;
  stroke: black;
  stroke-width: 1px;
  shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id='holder'></div>

【讨论】:

  • 这很酷,但是级别很低。我认为在这里使用色阶会更合适。
猜你喜欢
  • 2018-07-24
  • 2013-07-06
  • 1970-01-01
  • 2013-08-02
  • 2012-11-27
  • 2019-12-07
  • 1970-01-01
  • 2022-10-16
  • 2014-09-14
相关资源
最近更新 更多