Dash问题:无法在dcc.Graph上方显示dcc.Markdown内容
解决Dash中dcc.Graph无法添加dcc.Markdown的TypeError问题
问题原因
dcc.Graph组件不支持children属性,它的可视化内容完全由figure属性控制。你能在dash.DataTable上正常添加Markdown,是因为DataTable允许和其他组件共同作为容器的子元素,而你尝试给Graph添加Markdown时,错误地将Markdown嵌套在了Graph的属性层级里,导致dbc.Col组件检测到不符合要求的属性值,触发TypeError。
代码对比与修正
正常的DataTable示例(参考)
import dash import dash_bootstrap_components as dbc from dash import dash_table, dcc, html app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dbc.Container([ # 顶行:3个宽度为4的列 dbc.Row([ dbc.Col([ dcc.Markdown('### 数据表标题'), dash_table.DataTable( data=[{'col1': 'value1', 'col2': 'value2'}], columns=[{'name': '列1', 'id': 'col1'}, {'name': '列2', 'id': 'col2'}] ) ], width=4), # 另外两个列结构同理 ]), # 底行:2个宽度为6的列 dbc.Row([ # 其他列结构 ]) ]) if __name__ == '__main__': app.run_server(debug=True)
错误的Graph示例(触发TypeError)
# 错误写法:将Markdown作为Graph的子组件 dbc.Col([ dcc.Graph( figure={...}, children=[dcc.Markdown('### 图表标题')] # 此处为错误根源 ) ], width=4)
修正后的正确Graph示例
将dcc.Markdown和dcc.Graph并列放在dbc.Col的children列表中,作为同级组件:
import dash import dash_bootstrap_components as dbc from dash import dcc, html import plotly.express as px import pandas as pd app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) df = pd.DataFrame({'x': [1,2,3], 'y': [4,5,6]}) app.layout = dbc.Container([ # 顶行:3个宽度为4的列 dbc.Row([ dbc.Col([ dcc.Markdown('### 第一个图表标题'), dcc.Graph( id='graph-1', figure=px.line(df, x='x', y='y') ) ], width=4), dbc.Col([ dcc.Markdown('### 第二个图表标题'), dcc.Graph( id='graph-2', figure=px.bar(df, x='x', y='y') ) ], width=4), dbc.Col([ dcc.Markdown('### 第三个图表标题'), dcc.Graph( id='graph-3', figure=px.scatter(df, x='x', y='y') ) ], width=4) ]), # 底行:2个宽度为6的列 dbc.Row([ dbc.Col([ dcc.Markdown('### 底行第一个图表'), dcc.Graph( id='graph-4', figure=px.pie(df, values='y', names='x') ) ], width=6), dbc.Col([ dcc.Markdown('### 底行第二个图表'), dcc.Graph( id='graph-5', figure=px.area(df, x='x', y='y') ) ], width=6) ]) ]) if __name__ == '__main__': app.run_server(debug=True)
关键说明
- dbc.Col的children可以接受多个组件组成的列表,只要这些组件是合法的Dash组件即可。
- dcc.Graph的核心配置通过
figure属性完成,文本说明(比如标题)要么放在外部的dcc.Markdown/html.Hx组件中,要么直接在figure的布局(fig.update_layout(title='xxx'))里设置,不要试图给Graph添加子组件。
内容的提问来源于stack exchange,提问作者twelsh37
相关产品推荐
相关产品推荐

