简体   繁体   中英

How to add reference line to nvd3 discreteBarChart

I am working with the nvd3 discreteBarChart and want to add a reference line to the chart. I've seen the other posts which suggest using either MultiChart or LinePlusBarChart, but if I understand it correctly, in those charts, the bars are a series of values rather than discrete label/value pairs.

With the discreteBarChart, I can get the bars to display fine, but I can't figure out how to add the reference line. Here's the code:

Any ideas or tips on what I may be doing incorrectly?

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

I deleted this code from the above example:

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

Then, I modified the build.js file, under the discreteBarChart section to add this code:

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

Then add this after the // Zero line section of 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))
 ;}

Then in my code in my question above, I set the refValue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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