Dash框架输入产品名后dcc.Graph空白问题求助
解决Dash图表空白问题的方案
我仔细看了你的代码和控制台输出,发现两个核心问题导致图表空白,同时还有可以优化的地方,下面一步步帮你解决:
1. 图表Layout配置错误
你的figure里的layout部分,xaxis和yaxis直接写了字符串,这不符合Dash的格式要求——它们必须是字典类型,用来配置坐标轴的标题等属性。
原来的错误写法:
'layout':{ 'title':'Graphhhh', 'xaxis':'Month', 'yaxis':'Quantity' }
正确的写法应该是:
'layout':{ 'title':'Graphhhh', 'xaxis': {'title': 'Month'}, 'yaxis': {'title': 'Quantity'} }
这是导致图表空白的关键原因之一,Dash无法识别字符串格式的坐标轴配置。
2. 数据处理逻辑的Bug
你手动循环处理月份求和的代码存在两个问题:
- y变量未重置:每次回调时
y的初始值是上一次循环结束后的数值,不是0,导致后续计算的uni_quan数据错误。 - 集合去重打乱顺序:
uni_mon=list(set(mon))会把月份的顺序打乱,因为集合是无序的,图表展示的月份顺序会混乱。
其实完全可以用Pandas的groupby来简化这部分逻辑,既高效又能避免手动循环的错误:
# 按Month分组,对Bottle求和 df_grouped = df.groupby('Month')['Bottle'].sum().reset_index() # 直接提取x和y的数据 uni_mon = df_grouped['Month'].tolist() uni_quan = df_grouped['Bottle'].tolist()
修正后的完整代码
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input,Output import pandas as pd import mysql.connector db_connection = mysql.connector.connect( host="localhost", user="root", passwd="", db="trial" ) app = dash.Dash() app.layout = html.Div(children=[ html.H4('Sales Of February 2020 by MHD'), html.Label('Product Name: '), dcc.Input( id='tfield', placeholder='Enter the product name', type='text' ), html.Br(),html.Br(), html.Div([dcc.Graph(id='my-output')]) ]) @app.callback(Output('my-output','figure'),[Input('tfield', 'value')]) def callback(input_value): # 处理输入为空的情况,避免空输入时查询出错 if not input_value: return {'data': [], 'layout': {'title': 'Graphhhh', 'xaxis': {'title': 'Month'}, 'yaxis': {'title': 'Quantity'}}} df = pd.read_sql("select Month,Bottle from merge where Bottle>0 and ProductName=%s", db_connection, params=(input_value,)) # 用Pandas分组求和,简化逻辑同时避免错误 df_grouped = df.groupby('Month')['Bottle'].sum().reset_index() uni_mon = df_grouped['Month'].tolist() uni_quan = df_grouped['Bottle'].tolist() data = [{'x':uni_mon,'y':uni_quan,'type':'bar','name':input_value}] figure={ 'data':data, 'layout':{ 'title':'Graphhhh', 'xaxis': {'title': 'Month'}, 'yaxis': {'title': 'Quantity'} } } return figure if __name__ == '__main__': app.run_server(debug=False)
额外优化点
- 增加了输入为空的判断,避免空输入时数据库查询出错,同时返回空图表提示用户输入产品名。
- 去掉了冗余的
cursor变量,因为pd.read_sql会自动处理数据库游标。
这样修改后,你的图表应该就能正常显示数据了,而且代码更简洁易维护。
内容的提问来源于stack exchange,提问作者prateek_pro
相关产品推荐
相关产品推荐

