NVD3.js coloring specific bars in graph

前端 未结 2 919
时光取名叫无心
时光取名叫无心 2021-01-14 09:46

Is there a way to color specific bars? If a bar is less than the line, color it red.

Code: https://github.com/tvinci/webs/blob/gh-pages/lineplusbar.html

Exam

相关标签:
2条回答
  • 2021-01-14 10:34

    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().

    0 讨论(0)
  • 2021-01-14 10:43

    You can do:

    d3.selectAll("rect.nv-bar")
        .style("fill", function(d, i){
            return d.y > 50 ? "red":"blue";
        });
    
    0 讨论(0)
提交回复
热议问题