NVD3.js coloring specific bars in graph

孤人 提交于 2019-12-02 07:15:44

问题


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

Example: http://tvinci.github.io/webs/lineplusbar.html

I'd like to do something like this but the value for i is not the y value that I send in. It has been modified:

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

Data:

var overview_data=[
     {
        "key" : "Achieved",
        "bar": true,
        "values" : [ [ "1x" , 30] , [ "2x" , 70] , [ "3x" , 200] ]
     },
     {
        "key" : "Required",
        "values" : [ [ "1x" , 50] , [ "2x" , 100] , [ "3x" , 150] ]
     }
].map(function(series) {
    series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
    return series;
});

回答1:


You can do:

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



回答2:


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



来源:https://stackoverflow.com/questions/15947967/nvd3-js-coloring-specific-bars-in-graph

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