简体   繁体   中英

Formatting JSON from a Pandas data frame for Highcharts within a Django template

I have a Pandas data frame that I have converted to JSON like so:

json_data = data_df.to_json()

The original data frame looks like something similar to this:

    col1  col2  col3  col4
0     1     2     2    -1
1     2     4     3    -2
2     3     6     4    -3
3     4     8     5    -4
4     5     10    6    -5
...

And the JSON string looks similar to this:

[{"col1":1,"col2":2,"col3":2,"col4":-1},{"col1":2,"col2":4,"col3":3,"col4":-2},{"col1":3,"col2":6,"col3":4,"col4":-3},{"col1":4,"col2":8,"col3":5,"col4":-4}]

My Highcharts implementation is as follows:

$(document).ready(function() {

    var my_data = '{{ json_data }}'

    // create data chart
    $('#container').highcharts({
        chart: {
            renderTo: 'chart_panel',
            type: 'line',
        },
        legend: {layout: 'vertical',
                 align: 'right',
                 verticalAlign: 'middle',
                 borderWidth: 0,
        },
        title: {text: 'Roehrig Damper Data',
                x: -20 // center title
        },
        xAxis: {title: {text: 'Velocity (m/sec)'}},
        yAxis: {title: {text: 'Force (N)'}},
        series: [ {data: my_data} ],
    });

});

The {{ json_data }} is from my Django python view and I have confirmed that it's properly formatted through the browser console. Currently my code is only displaying a blank Highcharts chart with zero data being populated. I have tried a few different ways to manipulate the data that I desire, but without success.

My goal is to plot col2 against col1 and on the same chart plot col4 against col3 , or in other words the x-axis will be defined by both col1 and col3 .

Is there a way to accomplish my goal stated above, and if so, how?

Edit

With the help of @Andrew_Lvov I now have a JSON object that looks like this:

json_data = [
    {
        'name': "col1",
        'data': array([1, 2, 3, 4, 5])},
    {
        'name': "col2",
        'data': array([2, 4, 6, 8, 10])},
    // etc.
]

Now my problem is that it is adding the word array to the data.

Try

var myData = {{ json_data | safe }};

UPDATE :

Your data should be in format:

json_data = [
    {
        'name': "col1",
        'data': [1, 2, 3, 4, 5]},
    {
        'name': "col2",
        'data': [2, 4, 6, 8, 10]},
]

Series parameter:

        series: myData

UPDATE #2:

json_data = [{'data': list(value.values), 'name': key} for key, value in data_df.items()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM