NVD3.js coloring specific bars in graph

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 02:09:26

You can do:

d3.selectAll("rect.nv-bar")
    .style("fill", function(d, i){
        return d.y > 50 ? "red":"blue";
    });

The upward answer is right but it won't work when you change the data dynamically in my-case.

You can use the following configuration to get different bar colors based on the value.

var data=[ {
        "key": "data",
        "values": [
          {
            "x": 1,
            "y": 20
          },
          {
            "x": 2,
            "y": 15
          },
          {
            "x": 3,
            "y": 85
          },
          {
            "x": 4,
            "y": 66
          },}];

nv.addGraph(function() {
    var chart = nv.models.multiBarChart()
      .barColor(getColorArrayForGraph())
      .transitionDuration(350)
      .reduceXTicks(true)   
      .rotateLabels(0)      
      .showControls(true)   
      .groupSpacing(0.1);
    chart.xAxis
        .tickFormat(d3.format(',f'));

    chart.yAxis
        .tickFormat(d3.format(',.1f'));

    d3.select('#chart1 svg')
        .datum(data)
        .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
}

 // GET color array based on the value
  function getColorArrayForGraph() {
    let colorArray: any = [];
    for (let item of data) {
      if (item.y > 50) {
        colorArray.push('#FF0000');
      } else {
        colorArray.push('#004c00');
      }
    }
    return colorArray;
  };

So here, barcolor(["#FF0000","#00FFCC",....]) function takes arguments as array of colors.

This way you can get the array of colors and use it into barcolor().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!