javascript 如何为 angular-chart.js 中的每个条设置不同的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29999963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set different colours for each bar in angular-chart.js?
提问by Huey
I've looked at How to change colours for Angular-Chart.js, but it relates to colours for an entire (dataset), not a specific bar.
我看过如何更改 Angular-Chart.js 的颜色,但它与整个(数据集)的颜色有关,而不是特定的条。
What I'm looking for is a way to apply Different color for each bar in a bar chart; ChartJSto Angular.
我正在寻找的是一种为条形图中的每个条形应用不同颜色的方法;ChartJS到 Angular。
So, I've got a bar chart:
所以,我有一个条形图:
<canvas id="locationBar" class="chart chart-bar" data="chartParams.votes" labels="chartParams.listOfLocations" series="chartParams.series" colours="chartParams.colours" options="chartParams.options"></canvas>
With the following angular code (in a controller of course)
使用以下角度代码(当然在控制器中)
$scope.chartParams = {
listOfLocations: ['Trenzalore','Earth','Caprica','Sol','Tau Ceti'],
votes: [[5,10,6,7,2]],
series: ["Nice Places"],
colours: [{fillColor:getRandomColour()}],
options: {barShowStroke : false}
};
where getRandomColour()
would return a random colour.
哪里getRandomColour()
会返回随机颜色。
Right now, the colours
field applies this colour to all the bars:
现在,该colours
字段将此颜色应用于所有条形:
when I actually want a different colour for each bar:
当我真的想要每个条形不同的颜色时:
采纳答案by tpie
The easiest thing to do was to modify the chart.js source file to accept an array of colors for fillColor rather than a single color string.
最简单的做法是修改chart.js 源文件以接受fillColor 的颜色数组而不是单一颜色字符串。
If you could get one of the other proposed solutions working, I think it would end up having to be done in a very un-angular way.
如果你能让其他提议的解决方案之一起作用,我认为它最终将不得不以一种非常非角度的方式来完成。
Some people may not like tweaking the source, but for how simple and easy it was to do, and it achieves the desired result, and it isn't any less 'angular' in it's solution...let's just call it an improvement to chart.js.
有些人可能不喜欢调整源代码,但是因为它是多么简单和容易,并且它达到了预期的结果,而且它的解决方案并没有减少“角度”......让我们称之为改进图表.js。
Note that I only modified the "bar" chart to accept an array of colors, because it seems chart.js references the fillColor separately in each chart type. So you should be able to make this modification to work for any of the charts types.
请注意,我只修改了“条形”图表以接受颜色数组,因为似乎 chart.js 在每个图表类型中分别引用了 fillColor。因此,您应该能够进行此修改以适用于任何图表类型。
The place you need to modify:
需要修改的地方:
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
fillColor : dataset.fillColor[index], // <- added [index] here
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
This block of code can be found in the Chart.type.extend function for the bar chart. Just look for this:
此代码块可在条形图的 Chart.type.extend 函数中找到。只需寻找这个:
Chart.Type.extend({
name: "Bar",
and look further down inside that function for the place where it pushes the fillColor to the datasetObject.bars.
并在该函数内部进一步向下查看将 fillColor 推送到 datasetObject.bars 的位置。
Now just set up your chart like before, except feed it an array for fillColor:
现在只需像以前一样设置您的图表,除了为它提供一个填充颜色数组:
function($scope){
$scope.chartParams = {
listOfLocations: ['Trenzalore','Earth','Caprica','Sol','Tau Ceti'],
votes: [[5,10,6,7,2]],
series: ["Nice Places"],
colours: [{fillColor:["#FF0000", "#00FF00", "#0000FF", "#00FFFF", "#FFFF00"]}],
options: {barShowStroke : false}
};
}
回答by Dave Jarvis
Using the latest version of angular-chart.js, here's an example that changes the colours based on a condition, without modifying the library itself. Instead, it uses the chart-dataset-override
feature.
使用最新版本的angular-chart.js,这里有一个示例,它根据条件更改颜色,而无需修改库本身。相反,它使用该chart-dataset-override
功能。
The trick is to use a series with only one data set.
诀窍是使用只有一个数据集的系列。
HTML
HTML
<div ng-controller="chartControl">
<canvas id="bar" class="chart chart-bar"
chart-data="goal.data"
chart-labels="goal.labels"
chart-options="goal.options"
chart-series="goal.series"
chart-dataset-override="goal.datasetOverride"></canvas>
</div>
JavaScript
JavaScript
Add the following code to the controller:
将以下代码添加到控制器中:
var exceeded = '#27ae60';
var achieved = '#bdc3c7';
var defeated = '#e74c3c';
$scope.goal = [];
$scope.goal.goal = 3;
$scope.goal.series = [ 'Visits' ];
$scope.goal.labels = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'
];
$scope.goal.data = [
[5, 2, 3, 3, 3, 4, 2, 3, 4],
];
var backgroundColours = [];
// Assign the background colour based on whether the goal was achieved.
for( var i = 0; i < $scope.goal.data[0].length; i++ ) {
var v = $scope.goal.data[0][i];
if( v > $scope.goal.goal ) {
backgroundColours[i] = exceeded;
}
else if( v < $scope.goal.goal ) {
backgroundColours[i] = defeated;
}
else {
backgroundColours[i] = achieved;
}
}
// Create a place to hold the background colours.
$scope.goal.datasetOverride = [{ backgroundColor: [] }];
// Assign the colours to the pre-populated array.
$scope.goal.datasetOverride[0].backgroundColor = backgroundColours;
$scope.goal.options = {
barShowStroke: false,
scales: {
yAxes: [{
ticks: {
min: 0,
max: 7,
stepSize: 1
}
}]
}
};
Output
输出
Produces:
产生:
Related Links
相关链接
回答by Emil Ingerslev
One of the bigger problems with Chart libraries is that sooner or later you hit a wall, which can only be breached by hacking or extending the library. Knowing you hit that wall and what to could be the answer to this question.
Chart 库的一个更大问题是,您迟早会碰壁,而这只能通过黑客攻击或扩展库来突破。知道你撞到了那堵墙,什么可能是这个问题的答案。
Even though you can create a custom chart.js graph you could also solve it with d3.js. I've taken one of the basic angular d3.js barchart examples and added the behavior you want:
即使您可以创建自定义 chart.js 图形,您也可以使用 d3.js 解决它。我采用了基本的 angular d3.js 条形图示例之一,并添加了您想要的行为:
var colors = d3.scale.category10();
// ...
bars.enter().append('rect')
.classed('bar', true)
.attr({x: chartW,
width: barW,
y: function(d, i) { return y1(d); },
height: function(d, i) { return chartH - y1(d); },
fill: function(d,i) { return colors(i) }
})
// ...
http://plnkr.co/edit/9RCYAPCEj9iRsxkkYPaV?p=preview
http://plnkr.co/edit/9RCYAPCEj9iRsxkkYPaV?p=preview
Customizing a chart in any way, like changing fill, stroke or anything else is within reach. It is of cause still though a lot more code, but if you want to customize beyond library support, it is always a lot more code.
以任何方式自定义图表,例如更改填充、描边或其他任何东西都触手可及。原因仍然是更多的代码,但是如果您想在库支持之外进行自定义,则总是需要更多的代码。