0

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?

Kimlotte
  • 55
  • 6

2 Answers2

0

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

Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13
0

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/

ppotaczek
  • 36,341
  • 2
  • 14
  • 24
  • Am going to mark this as the correct answer to my question since it has worked for me. Follow up questions if you don't mind, 1. While dealing with local files in Django that need to be visualized, what efficient way would you recommend I go about it? 2. Why is the eval() option in the question above not recommended 3. Why was the code above not working in the first place? I do appreciate your answer a lot. – Kimlotte Feb 18 '22 at 11:39
  • 1. I definitely recommend you to use the timestamp format. 2. Please check this thread: https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea 3. The code was not working because your data was a string and it needs to be an array. – ppotaczek Feb 18 '22 at 11:47
  • Thank you for the reply. Would you clarify more on question 1 kindly. E.g I would store the files in this manner, then load them in here, and visualize them this way. Probably that the recommendation I would need. – Kimlotte Feb 18 '22 at 11:54
  • I am not a backend expert, but I would start with the proper data format (timestamp, y value) and find a different way to pass the data to Highcharts, maybe by using JSON? – ppotaczek Feb 21 '22 at 14:03