Flot Chart from Data Table

2019-08-06 18:52发布

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条回答
女痞
2楼-- · 2019-08-06 19:09

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.

查看更多
登录 后发表回答