将HighChart饼图创建为迷你图元素

时间:2017-04-20 20:42:00

标签: javascript jquery charts highcharts pie-chart

我需要使用动态的最小饼图填充数据表,有点像使用HighCharts的迷你图表。

我非常接近解决这个问题,但是通过数据 - 迷你线<td>参数传递数据数组是我的意思。

<td data-sparkline="[{name: 'KARE', y: 17.33, sliced: true, selected: true}, {name: 'KSTP', y: 14.03}, {name: 'WCCO', y: 10.38}, {name: 'KMSP', y: 3.2}]  ; pie"/>

这是我到目前为止所拥有的。

如果我在小提琴的第74行的函数中对图表数据进行硬编码,则图表会初始化并运行,但我需要该函数来读取表格中的数组。

 for (i = 0; i < len; i += 1) {
    $td = $($tds[i]);
    stringdata = $td.data('sparkline');
    arr = stringdata.split('; ');
    data = arr[0];
    chart = {};
            console.log(data);
    if (arr[1]) {
        chart.type = arr[1];
    }
    $td.highcharts('SparkLine', {
        series: [{
            data: [{name: 'KARE', y: 17.33, sliced: true, selected: true}, {name: 'KSTP', y: 14.03}, {name: 'WCCO', y: 10.38}, {name: 'KMSP', y: 3.2}],
            pointStart: 1
        }],

http://jsfiddle.net/8v63kxwp/3/

但是如果我循环遍历<td>并读取data-sparkline参数中的字符串,它会在控制台中记录正确的字符串,但不会绘制饼图。

for (i = 0; i < len; i += 1) {
    $td = $($tds[i]);
    stringdata = $td.data('sparkline');
    arr = stringdata.split('; ');
    data = arr[0];
    chart = {};
            console.log(data);
    if (arr[1]) {
        chart.type = arr[1];
    }
    $td.highcharts('SparkLine', {
        series: [{
            data: data,
            pointStart: 1
        }],

http://jsfiddle.net/8v63kxwp/2/

2 个答案:

答案 0 :(得分:1)

因为在第二种情况下数据只是一个字符串,你需要做一些像eval这样的对象属性很好的格式化

/**
 * Create a constructor for sparklines that takes some sensible defaults and merges in the individual
 * chart options. This function is also available from the jQuery plugin as $(element).highcharts('SparkLine').
 */
Highcharts.SparkLine = function (a, b, c) {
    var hasRenderToArg = typeof a === 'string' || a.nodeName,
        options = arguments[hasRenderToArg ? 1 : 0],
        defaultOptions = {
            chart: {
                renderTo: (options.chart && options.chart.renderTo) || this,
                backgroundColor: null,
                borderWidth: 0,
                type: 'area',
                margin: [2, 0, 2, 0],
                width: 160,
                height: 160,
                style: {
                    overflow: 'visible'
                },

                // small optimalization, saves 1-2 ms each sparkline
                skipClone: true
            },
            title: {
                text: ''
            },
            credits: {
                enabled: false
            },
            legend: {
                enabled: false
            },
        };

    options = Highcharts.merge(defaultOptions, options);

    return hasRenderToArg ?
        new Highcharts.Chart(a, options, c) :
        new Highcharts.Chart(options, b);
};

var start = +new Date(),
    $tds = $('td[data-sparkline]'),
    fullLen = $tds.length,
    n = 0;

// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
    var time = +new Date(),
        i,
        len = $tds.length,
        $td,
        stringdata,
        arr,
        labels,
        data,
        chart;

    for (i = 0; i < len; i += 1) {
        $td = $($tds[i]);
        stringdata = $td.data('sparkline');
        arr = stringdata.split('; ');
        data =arr[0];
        console.log(typeof(data));
        console.log(typeof(eval(data)));
        chart = {};
        if (arr[1]) {
            chart.type = arr[1];
        }
        $td.highcharts('SparkLine', {
            series: [{
                data: eval(data),
                pointStart: 1
            }],
            
                
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: false                
            }
        }
    },
            
            dataLabels: {
                enabled: false},
            
            tooltip: {
                headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
                pointFormat: '<b>{point.y}%</b>'
            },
            chart: chart
        });

        n += 1;

        // If the process takes too much time, run a timeout to allow interaction with the browser
        if (new Date() - time > 500) {
            $tds.splice(0, i + 1);
            setTimeout(doChunk, 0);
            break;
        }

       
    }
}
doChunk();
#result {
    text-align: right;
    color: gray;
    min-height: 2em;
}
#table-sparkline {
    margin: 0 auto;
    border-collapse: collapse;
}
th {
    font-weight: bold;
    text-align: left;
}
td, th {
    padding: 5px;
    border-bottom: 1px solid silver;
    height: 160px;
}

thead th {
    border-top: 2px solid gray;
    border-bottom: 2px solid gray;
}
.highcharts-tooltip>span {
    background: white;
    border: 1px solid silver;
    border-radius: 3px;
    box-shadow: 1px 1px 2px #888;
    padding: 8px;
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="result"></div>
<table id="table-sparkline">
    <thead>
        <tr>
            <th>State</th>
            <th>Income</th>
            <th>Income per quarter</th>
            <th>Costs</th>
            <th>Costs per quarter</th>
            <th>Result</th>
            <th>Result per quarter</th>
        </tr>
    </thead>
    <tbody id="tbody-sparkline">
        <tr>
            <th>Alabama</th>
            <td>254</td>
            <td data-sparkline="[{name: 'KARE', y: 17.33, sliced: true, selected: true}, {name: 'KSTP', y: 14.03}, {name: 'WCCO', y: 10.38}, {name: 'KMSP', y: 3.2}]  ; pie"/>
        </tr>
        <tr>
            <th>Alaska</th>
            <td>246</td>
            <td data-sparkline="[{name: 'KARE', y: 17.36, sliced: true, selected: true}, {name: 'KSTP', y: 14.03}, {name: 'WCCO', y: 10.38}, {name: 'KMSP', y: 3.2}]  ; pie"/>
        </tr>
    </tbody>
</table>

答案 1 :(得分:1)

当您从data-sparkline属性中读取数据时,它只是一个字符串,但Highcharts series需要一个数组。

因此,您需要将字符串解析为JavaScript数组。这通常是使用JSON.parse()完成的,但data-sparkline中的数据格式不正确JSON,因此在这种情况下,您可以改为使用eval()

http://jsfiddle.net/8v63kxwp/4/

注意:使用eval()时,请确保您了解并避免所涉及的安全风险:

Is Javascript eval() so dangerous?
Exploiting JavaScript's eval() method