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>