如何在Chart.js中将颜色系列设置为饼图 [英] How set color family to pie chart in chart.js

查看:217
本文介绍了如何在Chart.js中将颜色系列设置为饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Chart.js绘制饼图。我的值来自数据库,因此我不知道数据库中将有多少个值。在这里,我想为每个值设置一个唯一的颜色。以下是我的示例。

I am trying to draw a pie chart using Chart.js. My values are coming from a database hence I don't know how many values there are going to be in the database. Here I want to set set a unique color to each value. Below is my example.

var pieData = [
    {
        value: 20,
        color:"#878BB6"
    },
    {
        value : 40,
        color : "#4ACAB4"
    },
    {
        value : 10,
        color : "#FF8153"
    },
    {
        value : 30,
        color : "#FFEA88"
    }
];

var pieOptions = {
    segmentShowStroke : false,
    animateScale : true
}

var countries= document.getElementById("countries").getContext("2d");
        new Chart(countries).Pie(pieData, pieOptions);

当前在上面的示例中,我设置了硬编码值,但是在我的示例中,数据(Json)来自D B。

Currently in above example I have set hard coded values but in my example data (Json) is coming from DB.

推荐答案

您可以循环使用pieData数组,并为颜色值设置随机值。

You could loop thought your pieData array and set random values for the color value.

您可以使用 rgb(230,0,0)之类的值设置该值,并随机生成红色绿色蓝色整数值。

You can set this one with a value like "rgb(230,0,0)" and generate the red green blue integer values randomly.

类似这样的东西:

r = Math.floor(Math.random() * 200);
g = Math.floor(Math.random() * 200);
b = Math.floor(Math.random() * 200);
color = 'rgb(' + r + ', ' + g + ', ' + b + ')';

参见示例,其中包含随机值和随机颜色。 (运行几次以了解如何显示不同的数据集。)

See an example jsfiddle here, with random values and random colors. (Run it several times to get an idea of how it displays with different data sets.)

否则,您可以定义一组预定义的颜色并使用它。考虑到包含50多个项目的饼图不是很容易阅读。因此,默认列表50可能就可以了。

Or else you could define an array of predefined colors and just use that. Consider that a pie chart with more than 50 items is not very readeable. So a default list of 50 might just be ok.

这篇关于如何在Chart.js中将颜色系列设置为饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆