I’m trying to display pie and bar chart using Flask API on html page using chart.js. I am able to display pie chart but bar chart is getting below error.
“cannot read property of undefined (reading ‘offsetWidth’)” under “/nutrition_analysis” route.

Please find below Python main.py code,
# importing the necessary dependencies
from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import pandas as pd
from flask import send_file
#import matplotlib.pyplot as plt
#%matplotlib inline
import logging
from datetime import datetime
app = Flask(__name__) # initializing a flask app
@app.route('/', methods=['GET', 'POST']) # route to display the home page
@cross_origin()
def homePage():
return render_template("home.html")
@app.route('/form_fill',methods=['GET','POST']) # route to display the home page
@cross_origin()
def form_fill():
return render_template("form_fill.html")
@app.route('/download_file',methods=['GET','POST']) # route to display the home page
@cross_origin()
def download_file():
path = 'Daily Nutrition Requirement.xlsx'
return send_file(path, as_attachment=True)
@app.route('/nutrition_analysis',methods=['POST','GET']) # route to show the predictions in a web UI
@cross_origin()
def nutrition_analysis():
if request.method == 'POST':
try:
# reading the inputs given by the user
name = (request.form['name'])
age = float(request.form['age'])
weight = float(request.form['weight'])
reference = (request.form['reference'])
phone = float(request.form['phone'])
emailid = (request.form['emailid'])
file = request.form['customer_data']
customer_data = pd.read_excel(file)
RDA = pd.read_excel('Recommended_Nutrition.xlsx')
df = pd.concat([RDA, customer_data], ignore_index=True)
df_Carbs = df[df["Nutrients"] == "Carbohydrate"]
df_Fat = df[df["Nutrients"] == "Fats"]
df_Prot = df[df["Nutrients"] == "Proteins"]
df_Fbr = df[df["Nutrients"] == "Fiber"]
df_Macros = pd.concat([df_Carbs, df_Fat, df_Prot, df_Fbr])
df_Macros_Exp = df_Macros[df_Macros["Category"] == "Exp"]
# df_Macros_Obs = df_Macros[df_Macros["Category"] == "Obs"]
# plt.pie(df_Macros_Exp["Value"], labels=df_Macros_Exp["Nutrients"], autopct='%1.1f%%')
# plt.title("Expected Macros as per RDA", fontweight='bold')
# plt.savefig('chart.png')
values = df_Macros_Exp["Value"].tolist()
labels = df_Macros_Exp["Nutrients"].tolist()
colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA"]
# Bar Chart
df_stack = pd.merge(RDA,customer_data[['Nutrients','Value']],on='Nutrients', how='left')
df_stack1=df_stack[['Nutrients','Value_x','Value_y']].copy()
df_stack1["RDA"]=100
df_stack1["Intake"]=((df_stack1["Value_y"] - df_stack1["Value_x"])/df_stack1["Value_x"])*100
df_stack1.drop(["Value_x", "Value_y"], axis = 1, inplace = True)
def color(x):
if x < 0 or x > 50 :
return '#F7464A'
else:
return '#46BFBD'
df_stack1["Color"]=df_stack1["Intake"].apply(color)
values_bar = df_stack1["Intake"].tolist()
labels_bar = df_stack1["Nutrients"].tolist()
colors_bar = df_stack1["Color"].tolist()
#dt=datetime.now()
# showing the prediction results in a UI
return render_template('nutrition_analysis.html',s1=name,s2=age,s3=weight,s4=reference,s5=phone,s6=emailid,set=zip(values, labels, colors),set2=zip(values_bar,labels_bar,colors_bar))
except Exception as e:
print('The Exception message is: ',e)
logging.debug(e)
return 'something is wrong'
# return render_template('results.html')
else:
return render_template('home.html')
if __name__ == "__main__":
logging.basicConfig(filename='Nutrition_Analysis.log', level=logging.DEBUG)
app.run(host='127.0.0.1', port=8001, debug=True)
#app.run(debug=True) # running the app
Please find html page which need to be rendered below,
<head>
<meta charset="utf-8" />
<title>Macro Analysis</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>
<body>
<div class="item active" style="display: flex; height: 100px;">
<div style=" width: 30%;">
<h1><p>Liv365 Nutrition Analysis Report :</p></h1>
<br>name : {{s1}}</br>
<br>age : {{s2}}</br>
<br>weight : {{s3}}</br>
<br>reference : {{s4}}</br>
<br>phone : {{s5}}</br>
<br>emailid : {{s6}}</br>
</div>
<div style=" width: 30%;">
<h1>Macro Analysis</h1>
<canvas id="chart" width="400" height="200"></canvas>
<script>
var pieData = [
{% for values, labels, colors in set %}
{
value: {{values}},
label: "{{labels}}",
color : "{{colors}}"
},
{% endfor %}
];
// draw pie chart
new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData);
</script>
</div>
<div style=" width: 40%;">
<h1>Micro Analysis</h1>
<canvas id="bar" width="400" height="200"></canvas>
<script>
var barData = [
{% for values_bar, labels_bar, colors_bar in set2 %}
{
value: {{values_bar}},
label: "{{labels_bar}}",
color : "{{colors_bar}}"
},
{% endfor %}
];
new Chart(document.getElementById("bar"), {
type: 'bar',
data: {
labels: barData["label"],
datasets: [
{
label: "Population (millions)",
backgroundColor: barData["color"],
data: barData["value"]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Total Confirmed Cases of COVID in May'
}
}
});
</script>
</div>
</div>
</body>
</html>
Please help me resolve this issue.
Thanks in advance!!!
Regards,
Rohan