使用chart.js创建动态图表

时间:2014-10-23 04:34:08

标签: javascript jquery html charts

我正在使用Chart.js jquery插件来创建条形图。我可以创建静态图表,但我想创建一个动态图表。我想从从html表中读取的数据中绘制图表。如何将动态数据集设置为chart.js条形图。

这是我的代码。

<!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>

2 个答案:

答案 0 :(得分:7)

您可以使用jquery text()函数从表中提取值,通过为chart.js构建正确的数据结构,您可以从表中动态生成图表数据。

首先,你必须从表中提取标签。您可以选择行,通过迭代每一行,您可以从第一列获取标签数据。

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;
}

同样,您可以通过迭代表格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;
}

编写此函数后,您可以像这样修改barChartData

var barChartData = {
    labels : generateLabelsFromTable(),
    datasets : generateDataSetsFromTable()
}; 

您还应该在开头定义一个颜色数组,以保持图表的当前样式。在分配图表数据集

时,上面使用此数组
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)",
});

不要忘记包含jquery。

FIDDLE

答案 1 :(得分:1)

本页提及的所有答案均适用于ChartJs之前的版本,其中创建图表的方法完全不同

以前的版本

new Chart(ctx).Bar(barChartData, {
            responsive : true
        });

新版

new Chart(ctx,{
                  type: 'doughnut'
                 });

如果要为新版本创建动态图表,只需将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
                 });