我试图解析一个对象到chart.js而不是使用数组。这是我的对象:
var obj = {
"and":2,
"two":1,
"too":1,
"mother":2
}
我想解析我的obj
到chart.js,所以它创建一个图表从该对象的数据。例如,如果我们画一个柱状图,它会把and
放在前面,y轴上是2。然后是two
, y轴向上1,以此类推。
如何创建条形图:
var ctx = document.getElementById("myChart");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data
});
这是直接从他们的网站上取下来的。所有我需要的是改变从我的对象的关键的data.labels
和data.datasets[0].data
的值。这样做相对容易,因为我可以将对象转换为数组,但真正的问题是:是否可以将对象解析为图表的数据而不是数组?。谢谢!
与你在评论中所说的不同,实际上你可以做你想做的。
你只需要使用chart.js插件,它允许你在特定事件(如更新,渲染等)之前或之后处理你的图表,它们也很容易实例化:
Chart.pluginService.register({
beforeInit: function(chart) {
// This will be triggered before the chart is created
}
});
不用使用默认数据和标签创建图表,只需添加空数组,如下所示:
var data = {
labels: [],
datasets: [{
label: "My dataset",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: []
}]
};
然后在beforeInit
事件中,你只需要使用对象来填充这些数组:
beforeInit: function(chart) {
// This is where your chart data is stored
var data = chart.config.data;
// For each item in your object
for (var key in obj) {
// This is for security - check `http://stackoverflow.com/a/684692/4864023`
if (obj.hasOwnProperty(key)) {
// Add the key as a new xAxe label ...
data.labels.push(key);
// ... and the value as a new data
data.datasets[0].data.push(obj[key]);
}
}
}