d3.js图表​​区域填充不同的颜色 [英] d3.js chart area filling with different colors

查看:612
本文介绍了d3.js图表​​区域填充不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用不同的颜色填充图表下方的区域,具体取决于x值范围,例如,对于x值0到10黄色,从10到20红​​色等等。有没有办法做到这一点?

I'm attempting to fill the area under the graph with different colors, depending on x value ranges, say for example, for x values 0 to 10 yellow, from 10 to 20 red and so on. Is there a way to do that?

我的单一填充颜色的javascript是

My javascript for single fill color is

var m = 80; 
var w = 900 - 3*m;
var h = 600- 3*m; 

var x = d3.scale.linear().range([0, w]);
var y = d3.scale.linear().range([h, 0]);
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain(d3.extent(data, function(d) { return d.points; }));

var line = d3.svg.line()
.x(function(d) { 
return x(d.time); 
})

.y(function(d) { 
return y(d.points); 
})

var graph = d3.select("#graph").append("svg:svg")
           .attr("width", w+3*m)
           .attr("height", h+3*m)
           .append("svg:g")
           .attr("transform", "translate(" + 1.5*m + "," + 1.5*m + ")");

var area = d3.svg.area()
.x(function(d) { return x(d.time); })
.y0(h)
.y1(function(d) { return y(d.points); });

graph.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area)
.style("fill","steelblue"); 

提前致谢!

推荐答案

你基本上有两种选择。


  • 你可以为不同的颜色定义单独的区域。 / li>
  • 您可以定义单个区域并使用渐变来模拟不同的颜色。

第二个一个可能更容易,因为你不需要绘制任何单独的路径,你可以简单地填写你正在做的那个。

The second one is probably easier, as you don't need to draw any separate paths, you can simply fill the one like you're currently doing.

对于渐变,你需要定义停止(即颜色变化)以对应于值。特别是,您需要在同一个地方引入两个停靠点,使其看起来像颜色突然变化。有关渐变的更多信息此处。代码看起来像这样。

For the gradient, you would need to define the stops (i.e. colour changes) to correspond to the values. In particular, you would need to introduce two stops at the same place to make it appear like the colour is changing suddenly. More information on gradients here. The code would look something like this.

var grad = graph.append("defs")
     .append("linearGradient")
     .attr("id", "grad");
grad.append("stop").attr("offset", "0%").attr("stop-color", "yellow");
grad.append("stop").attr("offset", "10%").attr("stop-color", "yellow");
grad.append("stop").attr("offset", "10%").attr("stop-color", "red");
grad.append("stop").attr("offset", "20%").attr("stop-color", "red");
// etc

graph.append("path")
     .style("fill", "url(#grad)");

止损位置将由您的规模确定。

The positions of the stops would be determined by your scale.

这篇关于d3.js图表​​区域填充不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆