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

Streamlit中Matplotlib折线图图例与图表不匹配的修复方法

Streamlit折线图图例与实际数据不匹配问题解决

问题背景

在Streamlit应用中,通过侧边栏多选Spec选项后,折线图表的数据能正确更新,但图例标签与实际显示的曲线不匹配(例如图例显示Spec1,对应实际绘制的是Spec4的数据)。已尝试调整数据过滤条件、修改图例位置,问题仍未解决。

常见原因及对应解决方案

1. 图例标签未随过滤数据动态生成

如果代码中使用了固定的图例标签列表(比如原始数据的所有Spec值),而非基于选中的Spec动态生成,就会导致标签和曲线错位。

修复示例(Matplotlib):

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# 加载数据
df = pd.read_csv("your_data.csv")

# 侧边栏多选
selected_specs = st.sidebar.multiselect("选择Spec", df['Spec'].unique())

# 过滤数据
filtered_df = df[df['Spec'].isin(selected_specs)]

# 动态生成曲线与图例
fig, ax = plt.subplots()
# 严格按选中的Spec顺序绘制
for spec in selected_specs:
    spec_data = filtered_df[filtered_df['Spec'] == spec]
    ax.plot(spec_data['x_col'], spec_data['y_col'], label=spec)

ax.legend()
st.pyplot(fig)

修复示例(Plotly):

import streamlit as st
import pandas as pd
import plotly.express as px

df = pd.read_csv("your_data.csv")
selected_specs = st.sidebar.multiselect("选择Spec", df['Spec'].unique())
filtered_df = df[df['Spec'].isin(selected_specs)]

# 直接通过color参数绑定Spec列,自动生成对应图例
fig = px.line(filtered_df, x='x_col', y='y_col', color='Spec')
st.plotly_chart(fig)

# 或手动添加trace时指定name
import plotly.graph_objects as go
fig = go.Figure()
for spec in selected_specs:
    spec_data = filtered_df[filtered_df['Spec'] == spec]
    fig.add_trace(go.Scatter(x=spec_data['x_col'], y=spec_data['y_col'], name=spec))
st.plotly_chart(fig)

2. 数据分组顺序与选中顺序不一致

如果过滤后的数据分组顺序和selected_specs的顺序不匹配,循环绘图时会导致曲线和标签错位。解决方法是严格按照选中的Spec顺序来遍历绘图,而非直接遍历过滤后的数据分组。

3. 绘图库缓存或状态问题

Streamlit的组件状态可能导致绘图缓存异常,可以尝试:

  • 在绘图代码前添加st.cache_data.clear()(针对数据加载)或st.cache_resource.clear()(针对绘图对象),清除缓存后重新运行。
  • 确保每次绘图都是基于最新的selected_specs生成新的图表对象,而非复用旧对象。

验证步骤

  1. 在代码中添加打印语句,确认selected_specs的顺序和过滤后每个分组的Spec值一致:
st.write("选中的Spec顺序:", selected_specs)
st.write("过滤后的数据分组:", filtered_df['Spec'].unique().tolist())
  1. 运行应用,多选不同Spec组合,检查打印的顺序是否匹配,以及图表图例和曲线的对应关系。

内容的提问来源于stack exchange,提问作者Catherine Matje

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:15:03