简体   繁体   English

将SVG折线元素添加到折线图

[英]Adding SVG line element to line chart

Using nvd3 , I've created a simple interactive line chart. 使用nvd3 ,我创建了一个简单的交互式折线图。 I'm now wanting to add an svg line to the chart to show a baseline. 我现在想在图表中添加svg line以显示基线。

I have a function which when called, builds and places a line chart: 我有一个函数,当调用该函数时,它会构建并放置一个折线图:

function _buildGraph() {
  nv.addGraph(function() {
    chart = nv.models.lineChart()
      .options({
        duration: 300,
        useInteractiveGuideline: true
      });

    chart.xAxis
      .tickFormat(function(d) {
        return null
      })
      .staggerLabels(false);

    chart.yAxis
      .tickFormat(function(d) {
        if (d == null) {
          return 'N/A';
        }
        return d3.format(',.1f')(d);
      })
      .tickValues([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]);
    data = _sortData();

    // line code added here 

    d3.select('#potassium-profiler-container svg')
      .datum(data)
      .call(chart);

    nv.utils.windowResize(chart.update);
    return chart;
  });
}

To add the line, I've added the following code to the above function: 为了添加这一行,我在上面的函数中添加了以下代码:

var line = d3.select('#potassium-profiler-container svg').append('line')
  .attr('x1', chart.xAxis.scale()(0))
  .attr('x2', chart.xAxis.scale()(100))
  .attr('y1', chart.yAxis.scale()(4.5))
  .attr('y2', chart.yAxis.scale()(4.5))
  .attr('stroke-width', 2)
  .attr('stroke', 'red')

Given that I've specified the y1 attribute as 4.5, I would expect the line element to start from that position inside the chart svg. 假设我已将y1属性指定为4.5,则我希望该行元素从图表svg中的该位置开始。 Sadly, this is not the case. 可悲的是,事实并非如此。

Please see here for a minimal example of the issue. 在此处查看有关该问题的最小示例。

As you will see the line is actually displaying at a slightly higher position than specified so i'm wondering if maybe there's some margins that I have not comprehended? 如您所见,该行实际显示的位置比指定位置略高,所以我想知道是否存在一些我未理解的边距?

Any help would be greatly appreciated. 任何帮助将不胜感激。

Updated your plunk . 更新了您的朋克 The chart is drawn in a sub-group that is translated. 该图表绘制在一个已翻译的子组中。 You therefore need to add your line to that group (what I did), or translate your line of the same amount (harder for synchronization): 因此,您需要将行添加到该组中(我做了什么),或翻译相同数量的行(更难进行同步):

var line = d3.select('.nv-lineChart').append('line')
            .attr('x1', chart.xAxis.scale()(0))
            .attr('x2', chart.xAxis.scale()(100))
            .attr('y1', chart.yAxis.scale()(4.5))
            .attr('y2', chart.yAxis.scale()(4.5)) 
            .attr('stroke-width', 2)
            .attr('stroke', 'red') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM