chartjs动态创建数据数组 [英] chartjs creating data array dynamically
问题描述
我正在使用chartjs库创建一个饼图,并且想知道如何表示动态绘制图表所需要的值,
Im creating a Pie chart using chartjs library, and Im wondering how I could represent the values the will be need to render the chart dynamically,
在chartjs.org教程中,数据数组是这样表示的
In chartjs.org tutorial the array of data is represented like this
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
labelColor : 'white',
labelFontSize : '16'
},
{
value: 100,
color: "#46BFBD",
highlight: "#5AD3D1",
labelColor : 'white',
labelFontSize : '16'
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
labelColor : 'white',
labelFontSize : '16'
}
]
,数据将作为参数传递以呈现图表
and data will be pass as an argument to render the chart
new Chart(ctx).Pie(data);
然后呈现具有3个分区的图表:
this then renders a chart with 3 partitions:
但是说我想渲染X个分区,我该如何制作一个数据数组?
But say I want to render X partitions, how can i make an array of data?
我可以循环执行并将其附加到数据吗?
would I be able to do in a loop and append it to data?
到目前为止的代码:
function drawPie(ctx){
var newopts = {
inGraphDataShow: true,
inGraphDataRadiusPosition: 2,
inGraphDataFontColor: 'white',
}
//=========
// this should be dynamic (data will come the parameter)
//==========
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
labelColor : 'white',
labelFontSize : '16'
},
{
value: 100,
color: "#46BFBD",
highlight: "#5AD3D1",
labelColor : 'white',
labelFontSize : '16'
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
labelColor : 'white',
labelFontSize : '16'
}
]
new Chart(ctx).Pie(data, newopts);
}
推荐答案
您只需要按照Chart.js期望的饼状图生成数据结构,如果您不知道元素的最大数量,就可以生成饼图.颜色(如果您知道最大数量的元素,则可以从颜色数组中选择颜色).例如
You just need to generate the data structure in the way Chart.js expects for a pie chart and if you don't know the maximum number of element generate the colors (if you know the maximum number of elements, you could just pick it from a color array). For instance
var dynamicData = [
{ label: "One", value: 23 },
{ label: "Two", value: 33 },
{ label: "Three", value: 43 },
{ label: "Four", value: 53 },
]
dynamicData.forEach(function (e, i) {
e.color = "hsl(" + (i / dynamicData.length * 360) + ", 50%, 50%)";
e.highlight = "hsl(" + (i / dynamicData.length * 360) + ", 50%, 70%)";
// + any other code you need to make your element into a chart.js pie element
})
var ctx = document.getElementById("myChart").getContext("2d");
var myPieChart = new Chart(ctx).Pie(dynamicData);
小提琴- http://jsfiddle.net/k4ztyqzc/
这篇关于chartjs动态创建数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!