2013-04-11 47 views
2

有沒有辦法給特定的條打上顏色?如果一根線條小於線條,則將其着色爲紅色。NVD3.js給圖中的特定條着色

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

例子:http://tvinci.github.io/webs/lineplusbar.html

我想這樣做,但i值不是Y值,我在把它已被修改:

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

數據:

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

回答

5

你可以這樣做:

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

啊!非常好,謝謝。公認。 – user2265754 2013-04-11 22:37:36

0

向上的答案是正確的,但在我的情況下動態更改數據時它不起作用。

您可以使用以下配置根據值獲取不同的條形顏色。

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

所以在這裏,barcolor([ 「#FF0000」, 「#00FFCC」,...])函數採用作爲參數的顏色陣列。

這樣你可以得到顏色數組並將其用於barcolor()。

+0

在'linePlusBarChart'情況下不起作用。 BarColor函數沒有定義。 – saawsann 2018-01-30 15:35:23