2016-06-28 95 views
2

我想添加阴影到D3折线图的背景。该线的不同部分将会有不同的阴影。这里是一个example如何添加背景阴影到D3折线图

我的做法是添加矩形svg图表,但这似乎并没有工作,因为我不知道如何使宽度符合数据。

here is a jsfiddle

这里是矩形创作的一个例子:

svg.append("rect") 
    .attr("class", "shading") 
    .attr("x", d[1].date) 
    .attr("y", 80) 
    .attr("width", 20) 
    .attr("height", 20) 
    .attr("fill", "blue"); 

我在正确的轨道上?如何找到宽度以便与数据相符?

更新:会有多个不同宽度的正方形,所以我不能只抓住整个svg的宽度。

回答

0

与数据第一补SVG,然后之后得到了width属性,它会自动计算它

+0

有将是多个不同宽度的平方,所以我不能只抓住整个svg – auto

1

你可以这样说:

//get all the ticks in x axis 
//make a pair of it refer: d3.pair 
var data = d3.pairs(svg.selectAll(".x .tick").data()); 
    //make a color category 
var c10 = d3.scale.category10(); 
//to svg append rectangles 
svg.selectAll("rect") 
    .data(data)//for the tick pair 
     .enter() 
     .append("rect") 
    .attr("class", "shading") 
    .attr("x", function(d){return x(d[0])})//x will be the 1st tick 
    .attr("y", 0) 
    .attr("width", function(d){return (x(d[1]) - x(d[0]));})//width will be the diff of 1st and 2nd tick 
    .attr("height", height) 
    .attr("opacity", 0.2) 
    .attr("fill", function(d,i){return c10(i)});//use color category to color the rects. 

工作代码here

+1

的宽度来使用'd3.pairs'! –

+0

谢谢@GerardoFurtado – Cyril

+0

谢谢!但我有点困惑。我如何调整它,使广场可以是任何宽度,而不仅限于蜱?例如,你的例子,如果我想阴影是不同的twidths – auto