Home > Back-end >  Displaying Data in Django using HighCharts
Displaying Data in Django using HighCharts

Time:02-19

I have text data in a example.txt file in the following format

[[Date.UTC(1970, 10, 25), 0],
 [Date.UTC(1970, 11,  6), 0.25],
 [Date.UTC(1970, 11, 20), 1.41],
 [Date.UTC(1970, 11, 25), 1.64],
 [Date.UTC(1971, 0,  4), 1.6]]

Which I am reading in django view.py file as follows

filepath = os.getcwd()
f = open(filepath "/main/static/main/data/example.txt", "r")
dataset = f.read()

def home(request):
    context = {'dataset': dataset}
    return render(request, 'main/home.html', context)

Loading it in the template as follows

<script src="https://code.highcharts.com/highcharts.js"></script>
<div id='dataset' data-dataset={{ dataset }} style="width:100%; height:500px;"></div>
<script type="text/javascript" src="{% static 'main/js/main.js' %}" ></script>

And javascript main.js file with highchart code as follows

const app_control = (function() {
    var sdata;
    var init_charts;

    /*
    VARIABLES INITIALIZATIONS
    */

    /*
    DEFINE THE FUNCTIONS
    */  
    

    /*
    Initialize Functions
    */
    init_charts = function(sdata){
        const chart = Highcharts.chart('container', {
            chart: {
                type: 'spline'
            },
            title: {
                text: 'Example Data from '
            },
            xAxis: {
                type: "datetime",
                title: {
                    text: 'Date'
                }
            },
            yAxis: {
                title: {
                    text: 'Data in Y Axis'
                }
            },
            colors: ['#06C'],
            series: [{
                name:'Visualized Data',
                data: sdata
            }]
        })
    }

    /*
    PUBLIC INTERFACE
    */
    public_interface = {};

    /*
    RUN THE FUNCTIONS
    */
    $(function(){
        sdata = $('#TimeSeries').data('dataset');
        init_charts(sdata);
    });
    return public_interface;
}());

The question is, why is the data not visualizing? If you do console.log(sdata); you see the data, but it is not loading in HighCharts. What could be the reason for this behavior?

CodePudding user response:

If it is possible, you should change the data format in your file from Date.UTC(1970, 10, 25) to for example: 25660800000 (timestamp in milliseconds).

Live demo: http://jsfiddle.net/BlackLabel/t2rde3bk/


If you need to keep the current format, you can:

  • use eval -> data: eval(sdata) - definitely not recommended

Live demo: http://jsfiddle.net/BlackLabel/z45anjo7/


  • write a custom parser

const rows = sdata.split('Date.UTC(').slice(1);
const parsedData = [];

rows.forEach(row => {
  const splitted = row.split('),');
  const date = splitted[0];
  const y = splitted[1].split(']')[0];

  parsedData.push([
    Date.UTC(...date.split(',')),
     y
  ]);
});

const chart = Highcharts.chart('container', {
  ...,
  series: [{
    data: parsedData
  }]
})

Live demo: http://jsfiddle.net/BlackLabel/voe4q9bf/

CodePudding user response:

Because most probably the data is treated as string and not as a list of list or JSON list, check the types of the dataset in the charts function and you can JSON.parse to load the json from a string

  • Related