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

如何让Streamlit折线图在右侧Y轴展示df的终值?

实现右侧Y轴显示终值的方案

Streamlit 原生的 st.line_chart 是封装好的快捷组件,没有直接支持在右侧Y轴单独显示序列终值的配置项,不过可以通过Matplotlib或Altair这类更灵活的可视化库来实现需求,以下是两种可行方案:

方案一:Matplotlib + st.pyplot(自定义性强)

通过Matplotlib创建双Y轴,将右侧Y轴的刻度仅设置为目标终值,再用Streamlit渲染:

import matplotlib.pyplot as plt
import streamlit as st

# 获取数据
df = getDataFrame()['Change']
final_value = df.iloc[-1]

# 创建绘图对象
fig, ax_main = plt.subplots()

# 绘制主折线图
ax_main.plot(df.index, df.values, color='tab:blue')
ax_main.set_ylabel('Change')

# 添加右侧Y轴
ax_right = ax_main.twinx()
# 同步左右Y轴范围,避免错位
ax_right.set_ylim(ax_main.get_ylim())
# 仅显示终值作为右侧刻度
ax_right.set_yticks([final_value])
ax_right.set_ylabel('Final Value', color='tab:red')
ax_right.tick_params(axis='y', labelcolor='tab:red')

# 在Streamlit中展示图表
st.pyplot(fig)

方案二:Altair + st.altair_chart(更简洁的交互式方案)

利用Altair的文本标记功能,在图表右侧定位显示终值,同时保持Y轴范围匹配:

import altair as alt
import streamlit as st
import pandas as pd

# 获取数据并整理格式
df = getDataFrame()['Change'].reset_index()
df.columns = ['Date', 'Change']
final_value = df['Change'].iloc[-1]

# 绘制主折线图
line_chart = alt.Chart(df).mark_line(color='blue').encode(
    x='Date',
    y=alt.Y('Change', scale=alt.Scale(domain=[df['Change'].min(), df['Change'].max()]))
)

# 创建显示终值的文本标记
final_value_label = alt.Chart(pd.DataFrame({'value': [final_value]})).mark_text(
    align='right',
    baseline='middle',
    color='red',
    x=alt.value(-10)  # 相对于图表右侧的偏移量
).encode(
    y=alt.Y('value:Q', scale=alt.Scale(domain=[df['Change'].min(), df['Change'].max()])),
    text=alt.Text('value:Q', format='.2f')  # 格式化显示小数位数
)

# 组合图表并展示
combined_chart = line_chart + final_value_label
st.altair_chart(combined_chart, use_container_width=True)

两种方案都能实现你要的效果,可根据自己的可视化需求选择——Matplotlib适合需要高度自定义样式的场景,Altair则更适配Streamlit的交互式体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:06:29