Flot Chart from Data Table

半世苍凉 提交于 2020-01-05 08:03:12

问题


I want to build a flot chart from a table. The table is built using the jquery datatables plugin. The table can be edited inline.

I was wondering if anyone had any tips to display the data in flot. Would you pull the data from json or directly from the chart to build the flot chart?

The data is populated in dynamically using the datatables jquery plugin.

The table looks like this..

<div id="plotarea">  
    <table>  
        <caption>GDP, based on exchange rates, over time. Values in billion USDs.</caption>  
        <tr>  
            <td></td>  
            <th scope="col">2003</th>  
            <th scope="col">2002</th>  
            <th scope="col">2001</th>  
            <th scope="col">2000</th>  
            <th scope="col">1999</th>  
            <th scope="col">1998</th>  
        </tr>  
        <tr>  
            <th scope="row">USA</th>  
            <td>10,882</td>  
            <td>10,383</td>  
            <td>10,020</td>  
            <td>9,762</td>  
            <td>9,213</td>  
            <td>8,720</td>  
        </tr>  
        <tr>  
            <th scope="row">EU</th>  
            <td>10,970</td>  
            <td>9,040</td>  
            <td>8,303</td>  
            <td>8,234</td>  
            <td>8,901</td>  
            <td>8,889</td>  
        </tr>          
    </table>  
</div>

Thanks!


回答1:


You can use loops to go through your table and build the data array for flot. Something like this:

    var headerTr = $('table tr:first()');
    var rowCount = $('table tr').length - 1;
    var data = [];        

    for (var row = 0; row < rowCount; row++) {
        var tr = $('table tr').eq(row + 1);
        var dataseries = {
            label: tr.find('th').text(),
            data: []
        };
        for (var col = 0; col < tr.find('td').length; col++) {
            var xval = headerTr.find('th').eq(col).text();
            var yval = tr.find('td').eq(col).text().replace(',', '');
            dataseries.data.push([xval, yval]);
        }
        data.push(dataseries);
    };

Here is a fiddle with a working example. The drawing is started by button click. For your datatables you could change that to an onchange event or something similar.



来源:https://stackoverflow.com/questions/15991519/flot-chart-from-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!