如何在D3折线图中添加背景阴影

时间:2016-06-28 05:50:30

标签: javascript d3.js svg

我想在D3线图的背景中添加阴影。线的不同部分会有不同的阴影。这是example

我的方法是向图表添加矩形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");

我是否在正确的轨道上?如何找到宽度以使其与数据相对应?

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

2 个答案:

答案 0 :(得分: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 :(得分:0)

首先用数据填充svg,然后在获取width属性之后,它应该自动计算它

相关问题