Skip to content
Advertisement

How to pass a dictionary to ChartJS?

I’m trying to pass a dictionary from my Flask file to my ChartJS but the data doesn’t load on my chart. I think there’s a problem on passing my data. Here is the format of my dictionary. Basically, it’s a time series dataframe I converted as dict.

[{'dates': Timestamp('2021-12-31 00:00:00'), 'cases': 2},
 {'dates': Timestamp('2022-01-01 00:00:00'), 'cases': 0},
 {'dates': Timestamp('2022-01-02 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-03 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-04 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-05 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-06 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-07 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-08 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-09 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-10 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-11 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-12 00:00:00'), 'cases': 1},
 {'dates': Timestamp('2022-01-13 00:00:00'), 'cases': 1}] 

Here is my flask file:

@app.route("/forecast-calculation", methods=["POST"])
    def get_result():
        days_ahead = 13
        time_steps = 30
        if request.method == "POST":
            file = request.files['file']
            basepath = os.path.dirname(__file__)
            path = os.path.join(basepath, "user-uploads", file.filename)
            df = file.save(path)
            model, scaler, df = forecast.load(path)
            pred_values = forecast.forecast(df, days_ahead, model, time_steps, scaler)
            dict = forecast.final_df(df, pred_values, days_ahead, scaler)
        return render_template("forecast-calculation.html", dict = dict)

Here is my HTML file

<canvas id="forecastCalculationchart"></canvas>
          <script>
            var parsed = JSON.parse('{{dict | tojson}}');
            labels = parsed.dates.map(function(elem){
              return elem.labels;
            })
            cases = data.cases.map(function(elem){
              return elem.cases;
            })
                const forecastCalculation = document.getElementById('forecastCalculationchart');
                const forecastCalculationchart = new Chart(forecastCalculation, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            data:cases,       
                            backgroundColor: '#001F23',
                            borderColor: '#001F23',
                            borderWidth: 2,
                            tension: 0.2
    
                        }]
                    },
                    options: {
                      plugins: {
                          legend: {
                              display: false
                          }
                      }
                  }
                      
                });
            </script>

Advertisement

Answer

I solved it, what I did was to converted my result to list intead of dataframe and created a list of tuples, then passed it on my jinja file.

Here’s my python file:

 pred_dates = predict_dates(df, days_ahead)
 dates_list = [t.strftime("%Y-%m-%d") for t in pred_dates]
        
 forecasted_cases = np.asarray(pred_cases, dtype=np.int64)
 forecasted_cases = forecasted_cases.tolist() 
    
 forecasted_tuple = [(dates_list[i], forecasted_cases[i]) 
 for i in range(0, len(dates_list))]
 return forecasted_tuple

And my controller:

 pred_values = forecast.forecast(df, days_ahead, model, time_steps, scaler)
 forecasted_tuple = forecast.get_result(df, pred_values, days_ahead, scaler)

 labels = [row[0] for row in forecasted_tuple]
 values = [row[1] for row in forecasted_tuple]
 return render_template("forecast-calculation.html", labels=labels, values=values)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement