如何将参考线添加到 nvd3 discreteBarChart

How to add reference line to nvd3 discreteBarChart

我正在使用 nvd3 discreteBarChart 并想向图表添加参考线。我看过其他建议使用 MultiChart 或 LinePlusBarChart 的帖子,但如果我理解正确,在这些图表中,条形图是一系列值而不是离散的 label/value 对。

使用 discreteBarChart,我可以让条形图正常显示,但我不知道如何添加参考线。这是代码:

关于我可能做错了什么的任何想法或提示?

// Make empty data container
var data = [
{
   key: "salaries",
   values: []
}];

// Fetch data
d3.tsv("00_d3_Bar-MedianSalaries_nv2.txt", function (error, datafile) {
if (error) return console.log("there was an error loading the data file: " + error);

  datafile.forEach(function(d){
    d.value=+d.value;
   data[0].values.push(d)    
  });
});

// Add chart to display
nv.addGraph(function() {
    var chart = nv.models.discreteBarChart()
        .x(function(d) { return d.label })
        .y(function(d) { return d.value })
        .showLegend(false)
    .showXAxis(true)
    .showYAxis(true)
    .rightAlignYAxis(false)
    .staggerLabels(false)
        .showValues(false)
    .wrapLabels(false)
    .rotateLabels(-45)
    .duration(250)
        .margin({left:100,bottom:250,top:20})
    .width(800)
    .height(600)
    ;

chart.yAxis
    .axisLabel('Median Salary')
    .tickFormat(d3.format('$,.0f')) // formatted for currency
    .axisLabelDistance(10)
    ;
d3.select('#chart1 svg')
        .datum(data)
        .call(chart);

d3.select('#chart1 svg')
        .append('line')
    .attr("x1", 0)
    .attr("y1", 38500)
    .attr("x2", 0)
    .attr("y2", 38500);

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

我从上面的例子中删除了这段代码:

d3.select('#chart1 svg') 
  .append('line')
.attr("x1", 0)
.attr("y1", 38500)
.attr("x2", 0)
.attr("y2", 38500);

然后,我修改了build.js文件,在discreteBarChart部分下添加了这段代码:

gEnter.append('g').attr('class', 'nv-barsWrap');`
gEnter.append('g').attr('class','nv-refLine') // new code`
      .append('line'); // new code`

然后在代码的 // 零线部分之后添加这个

// Reference line  -- new code
if (refValue >0) {
 g.select(".nv-refLine line")
  .style('stroke','black')
  .attr("x1",0)
  .attr("x2",(rightAlignYAxis) ? -availableWidth : availableWidth)
  .attr("y1", yAxis.scale()(refValue))
  .attr("y2", yAxis.scale()(refValue))
 ;}

然后在我上面问题的代码中,我设置了 refValue。