如何将参考线添加到 nvd3 离散条形图

How to add reference line to nvd3 discreteBarChart

本文关键字:nvd3 条形图 添加 参考      更新时间:2023-09-26

我正在使用 nvd3 离散条形图,并希望为图表添加参考线。我看过其他建议使用MultiChart或LinePlusBarChart的文章,但是如果我理解正确的话,在这些图表中,条形是一系列值,而不是离散的标签/值对。

使用离散条形图,我可以让条形显示正常,但我无法弄清楚如何添加参考线。代码如下:

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

// 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);

然后,我在离散BarChart部分下修改了build.js文件以添加以下代码:

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。