为svg图提供背景颜色,直到特定线覆盖的区域

时间:2017-06-28 02:37:19

标签: javascript css d3.js svg time-series

下面是我的D3图表,呈现此图表的代码是:

<!DOCTYPE html>
<svg width="960" height="200"></svg>
<link rel="stylesheet" href="https://mcaule.github.io/d3-timeseries/src/d3_timeseries.css" type="text/css">
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://mcaule.github.io/d3-timeseries/src/d3_timeseries.js"></script>
<script>

  var data =    [{
                    "timestamp": "2017-06-23T19:03:00-07:00",
                    "a_1": 21.100729166695746,
                    "a_2": 13.862652074746523
                },
                {
                    "timestamp": "2017-06-23T19:03:10-07:00",
                    "a_1": 21.09999908563894,
                    "a_2": 13.865705100895076
                },
                {
                    "timestamp": "2017-06-23T19:03:20-07:00",
                    "a_1": 21.099269029842795,
                    "a_2": 13.965687962747438
                },
                {
                    "timestamp": "2017-06-23T19:03:30-07:00",
                    "a_1": 21.098538999306424,
                    "a_2": 14.072341340713344
                },
                {
                    "timestamp": "2017-06-23T19:03:40-07:00",
                    "a_1": 21.097808994028977,
                    "a_2": 14.105108226640267
                },
                {
                    "timestamp": "2017-06-23T19:03:50-07:00",
                    "a_1": 21.097079014009566,
                    "a_2": 14.431892151709313
                },
                {
                    "timestamp": "2017-06-23T19:04:00-07:00",
                    "a_1": 21.096349059247324,
                    "a_2": 13.827938924324112
                },
                {
                    "timestamp": "2017-06-23T19:04:10-07:00",
                    "a_1": 21.09561912974137,
                    "a_2": 13.90099860030143
                }]

data.map(function(ele,index){
    ele.timestamp = new Date(ele.timestamp);
});

var chart = d3.timeseries();

chart.addSerie(data.slice(0,3), {
    x: 'timestamp',
    y: 'a_1'
  }, {
    interpolate: 'linear',
    color: "#505050",
    label: "value_1"
  });

  chart.addSerie(data.slice(4), {
    x: 'timestamp',
    y: 'a_2'
  }, {
    interpolate: 'linear',
    color: "#A9A9A9",
    label: "value_2"
  });

chart.width(900)

chart("body")

</script>

我在下图中描述了我的问题:

Need to have some background color the first series added in graph, couldn't figure out how to do that.Please suggest

1 个答案:

答案 0 :(得分:0)

使用此库可以做的最好的事情是为每个始终为baseline的点添加额外的0值。然后,您可以使用color绘制一个差异来填充基线和值之间的区域:

.addSerie(
    data.slice(0,60),
    { x: 'date', y: 'n', diff: 'baseline' },
    { interpolate: 'linear', color: "#a6cee3", label:"value" }
)

data.slice(0,60)应作为示例,其中背景将限制在前60个数据点。您应该选择下面要绘制背景的所有数据点,并将所有其他数据点保留在本系列之外。