如何在D3折线图中添加背景底纹 [英] How to add background shading to D3 line chart

查看:71
本文介绍了如何在D3折线图中添加背景底纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在D3折线图的背景上添加阴影.线的不同部分会有不同的阴影.这是一个示例

I would like to add shading to the background of a D3 line graph. There would be different shades for different parts of the line. Here is an example

我的方法是在图表中添加矩形svg,但这似乎不起作用,因为我不知道如何使宽度与数据相对应.

My approach is the add rectangle svg to the chart, but that doesn't seem to be working because I don't know how to make the width correspond with the data.

这是一个jsfiddle

以下是创建矩形的示例:

Here is an example of the rectangle creation:

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

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

Am I on the right track? How do I find the width so that it corresponds with the data?

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

UPDATE: There will be multiple square of different widths, so I can't just grab the width of the entire svg.

推荐答案

您可以这样做:

 //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.

工作代码此处

这篇关于如何在D3折线图中添加背景底纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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