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

在Streamlit中为Plotly子图添加标签与自定义图例的实现方法

给Plotly子图添加轴标签与自定义图例的修改方案

问题描述

我正在使用Streamlit结合Plotly绘制子图,现有代码如下:

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import streamlit as st

#index is date
fig1 = px.line(plot_df2,y=['price','counting'],template="plotly_dark"})
fig2 = px.line(plot_df3,y=['price','counting'],template="plotly_dark")
fig = make_subplots(rows=1, cols=2)
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig1['data'][1], row=1, col=1)
fig.add_trace(fig2['data'][0], row=1, col=2)
fig.add_trace(fig2['data'][1], row=1, col=2 
st.plotly_chart(fig, theme=None, use_container_width=True)     

希望为图表添加price、counting这类轴标签,并添加如‘the dataset plot’的自定义图例,请问该如何修改上述代码?

修改后的完整代码

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import streamlit as st

# index is date
fig1 = px.line(plot_df2, y=['price','counting'], template="plotly_dark")
fig2 = px.line(plot_df3, y=['price','counting'], template="plotly_dark")

# 创建子图,可按需添加子图标题
fig = make_subplots(rows=1, cols=2, subplot_titles=("数据集图表1", "数据集图表2"))

# 添加轨迹并自定义图例名称
fig.add_trace(fig1['data'][0].update(name='price'), row=1, col=1)
fig.add_trace(fig1['data'][1].update(name='counting'), row=1, col=1)
fig.add_trace(fig2['data'][0].update(name='price'), row=1, col=2)
fig.add_trace(fig2['data'][1].update(name='counting'), row=1, col=2)

# 设置每个子图的轴标签
fig.update_xaxes(title_text="日期", row=1, col=1)
fig.update_yaxes(title_text="数值", row=1, col=1)
fig.update_xaxes(title_text="日期", row=1, col=2)
fig.update_yaxes(title_text="数值", row=1, col=2)

# 设置整体图表标题(即你需要的自定义图例类标题)
fig.update_layout(title_text="the dataset plot", template="plotly_dark")

st.plotly_chart(fig, theme=None, use_container_width=True)

关键修改说明

  • 修正原代码语法错误:移除fig1中template参数后多余的},补全最后一行add_trace的闭合括号
  • 自定义图例名称:通过update(name='xxx')为每条曲线设置明确的图例名称(price、counting)
  • 添加轴标签:使用update_xaxes和update_yaxes,通过row和col指定子图位置,分别设置x轴(日期)和y轴(数值)标签
  • 添加整体图表标题:通过update_layout的title_text设置你需要的‘the dataset plot’标题,同时保留plotly_dark模板风格
  • 可选子图标题:创建子图时通过subplot_titles参数为每个子图添加单独标题,按需保留即可

内容的提问来源于stack exchange,提问作者royaeh azadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:55:17