You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Plotly Express图表设置标题?多DataFrame绘图问题解决

解决Plotly绘制DataFrame列表柱状图添加标题的问题

首先明确:完全可以用fig.update_layout()方法给图表添加标题,这是Plotly官方推荐的修改布局(包括标题)的方式,比在px.bar()里传title参数更灵活。

你之前用df.text出错的原因很简单:Pandas的DataFrame对象根本没有text这个属性,这个写法本身就不对,自然拿不到想要的标题内容。

要给每个DataFrame对应的图表加上正确的标题,有两种实用方案:

方案1:给DataFrame设置name属性,直接调用

如果你的每个DataFrame可以提前设置一个标识性的name(比如代表分组、地区等信息),就能直接用这个属性当标题:

def generate_bar_plot(list_of_dfs):
    for idx, df in enumerate(list_of_dfs): 
        fig = px.bar(df, x='Month', y='Transportation_Cnt', color='Transportation')
        # 用update_layout设置标题,优先用df.name,没有就用默认序号
        fig.update_layout(title=df.name if hasattr(df, 'name') else f"第{idx+1}个图表")
        fig.update_xaxes(tickmode='linear')
        fig.show()

# 提前给每个DataFrame设置name属性
for i, df in enumerate(all_avg_cnt_by_month_list):
    df.name = f"{i+1}号线月度交通统计"

generate_bar_plot(all_avg_cnt_by_month_list)

方案2:单独传入标题列表,一一对应

如果不方便给DataFrame加属性,直接把标题列表和DataFrame列表一起传入函数,用zip()配对:

def generate_bar_plot(list_of_dfs, plot_titles):
    # 确保标题数量和DataFrame数量一致
    if len(list_of_dfs) != len(plot_titles):
        raise ValueError("DataFrame列表和标题列表长度不匹配")
    
    for df, title in zip(list_of_dfs, plot_titles): 
        fig = px.bar(df, x='Month', y='Transportation_Cnt', color='Transportation')
        fig.update_layout(title=title)
        fig.update_xaxes(tickmode='linear')
        fig.show()

# 定义对应每个图表的标题
titles = ["早高峰月度交通统计", "晚高峰月度交通统计", "平峰月度交通统计"]
generate_bar_plot(all_avg_cnt_by_month_list, titles)

另外补充:你之前在px.bar()里写title={title}是多余的,直接传title=title就行,用大括号会把标题变成集合类型,反而可能显示异常。

内容的提问来源于stack exchange,提问作者Justin White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:05:17