Javascript 使用 chart.js 创建动态图表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26521352/
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
Create dynamic chart with chart.js
提问by Daybreaker
I am using Chart.js jquery plugin to create bar chart . I can create static chart but i want to create a dynamic chart. I want to draw the chart from the data which read from a html table. How to set dynamic dataset to a chart.js bar chart.
我正在使用 Chart.js jquery 插件来创建条形图。我可以创建静态图表,但我想创建一个动态图表。我想从从 html 表中读取的数据中绘制图表。如何将动态数据集设置为 chart.js 条形图。
This is my code.
这是我的代码。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Bar Chart</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script src="js/Chart.js"></script>
</head>
<body>
<div style="width:50%;">
<canvas id="canvas_bar"></canvas>
</div>
<div class="dataset">
<table>
<tr>
<th>Year</th>
<th>Income</th>
<th>Expenditure</th>
<th>Profit/Loss<th>
</tr>
<tr>
<td>2012</td>
<td>10000</td>
<td>5000</td>
<td>5000</td>
</tr>
<tr>
<td>2013</td>
<td>11500</td>
<td>7500</td>
<td>4000</td>
</tr>
<tr>
<td>2014</td>
<td>9800</td>
<td>4700</td>
<td>5100</td>
</tr>
<table>
<div>
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var barChartData = {
labels : ["2012","2013","2014"],
datasets : [
{
fillColor : "rgba(95,137,250,0.5)",
strokeColor : "rgba(95,137,250,0.9)",
highlightFill: "rgba(95,137,250,0.75)",
highlightStroke: "rgba(95,137,250,1)",
data : [10000,11500,9800]
},
{
fillColor : "rgba(245,75,75,0.5)",
strokeColor : "rgba(245,75,75,0.8)",
highlightFill : "rgba(245,75,75,0.75)",
highlightStroke : "rgba(245,75,75,1)",
data : [5000,7500,4700]
},
{
fillColor : "rgba(98,223,114,0.5)",
strokeColor : "rgba(98,223,114,0.8)",
highlightFill : "rgba(98,223,114,0.75)",
highlightStroke : "rgba(98,223,114,1)",
data : [5000,4000,5100]
}
]
};
window.onload = function(){
var ctx = document.getElementById("canvas_bar").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}
</script>
</body>
</html>
回答by Alper Cinar
you can extract values from table by using jquery text() function , by building correct data structure for chart.js you can generate chart data dynamically from table .
您可以使用 jquery text() 函数从 table 中提取值,通过为 chart.js 构建正确的数据结构,您可以从 table 动态生成图表数据。
First of all you have to extract labels from table . you can select rows and by iterating each row you can get label data from first columns.
首先,您必须从 table 中提取标签。您可以选择行,通过迭代每一行,您可以从第一列获取标签数据。
function generateLabelsFromTable()
{
var labels = [];
var rows = jQuery("tr");
rows.each(function(index){
if (index != 0) // we dont need first row of table
{
var cols = $(this).find("td");
labels.push(cols.first().text());
}
});
return labels;
}
Similarly you can generate chart data by iterating the table html .
同样,您可以通过迭代表 html 来生成图表数据。
function generateDataSetsFromTable()
{
var data;
var datasets = [];
var rows = jQuery("tr");
rows.each(function(index){
if (index != 0) // we dont need first row of table
{
var cols = $(this).find("td");
var data = [];
cols.each(function(innerIndex){
if (innerIndex!=0) // we dont need first columns of the row
data.push($(this).text());
});
var dataset =
{
fillColor : colors[index%3].fillColor,
strokeColor : colors[index%3].strokeColor,
highlightFill: colors[index%3].highlightFill,
highlightStroke: colors[index%3].highlightStroke,
data : data
}
datasets.push(dataset);
}
});
return datasets;
}
After writing this functions , you can modify your barChartData like this
编写此函数后,您可以像这样修改 barChartData
var barChartData = {
labels : generateLabelsFromTable(),
datasets : generateDataSetsFromTable()
};
You also should define a color array into the begining to keep the current style of the chart . This array is used above when assigning chart dataset
您还应该在开始时定义一个颜色数组以保持图表的当前样式。上面在分配图表数据集时使用此数组
var colors = [];
colors.push(
{
fillColor : "rgba(95,137,250,0.5)",
strokeColor : "rgba(95,137,250,0.9)",
highlightFill: "rgba(95,137,250,0.75)",
highlightStroke: "rgba(95,137,250,1)"
});
colors.push(
{
fillColor : "rgba(245,75,75,0.5)",
strokeColor : "rgba(245,75,75,0.8)",
highlightFill : "rgba(245,75,75,0.75)",
highlightStroke : "rgba(245,75,75,1)"
});
colors.push(
{
fillColor : "rgba(98,223,114,0.5)",
strokeColor : "rgba(98,223,114,0.8)",
highlightFill : "rgba(98,223,114,0.75)",
highlightStroke : "rgba(98,223,114,1)",
});
Do not forget to include jquery .
不要忘记包含 jquery 。
回答by Vaimeo
All answers mention on this page is for ChartJs previous version in which method for creating chart is totally different
此页面上提到的所有答案都是针对 ChartJs 以前的版本,其中创建图表的方法完全不同
Previous version
上一版本
new Chart(ctx).Bar(barChartData, {
responsive : true
});
New Version
新版本
new Chart(ctx,{
type: 'doughnut'
});
If you want to create Dynamic Chart for New Version then just append the convas in any container you want then call chart method Full code is this
如果您想为新版本创建动态图表,那么只需将 convas 附加到您想要的任何容器中,然后调用图表方法完整代码是这样的
$('#pieChartContainer').html('');
$('<canvas id="pieChart"></canvas>').appendTo($("#pieChartContainer"));
data1={};
data1.labels=["M", "T", "W", "T", "F", "S", "S"];
data1.datasets=[
{backgroundColor:["#2ecc71","#3498db","#95a5a6","#9b59b6","#f1c40f","#e74c3c","#34495e"],data: [12, 19, 3, 17, 28, 24, 7]}
];
var ctx = $("#pieChart").get(0).getContext("2d");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: data1
});

