如何用Streamlit将CSV数据转换为折线图并实现指标选择功能
修复Streamlit学生身高/体重折线图展示功能
需求说明
使用Streamlit的selectbox组件,选择CSV文件中的**Height(身高)或Weight(体重)数据,以学生Name(姓名)**为X轴,选中的指标为Y轴,在Streamlit中展示折线图。
CSV数据示例
Class,Name,Sex,Height,Weight A01,Canning,F,160,45 A01,Mike,M,172,70 A01,Cena,M,190,80 A01,Nick,M,169,76 A02,Tomy,M,174,65 A02,Ray,F,158,47 A02,Ting,F,172,43 A02,Weng,M,179,68 A03,Jennie,F,156,44 A03,Wex,M,171,82 A03,Jeff,M,166,69 A03,Rudy,M,167,79
现有代码问题
st.line_chart参数调用错误:传入了matplotlib轴对象,且x/y参数格式完全不符合要求- 逻辑顺序颠倒:先执行绘图代码再显示选择框,导致选择无法影响图表结果
- Streamlit环境中
plt.show()无效,需用st.pyplot()渲染matplotlib图形 - 未实现选择结果与图表数据的联动逻辑
修正后的完整代码
import pandas as pd import streamlit as st import matplotlib.pyplot as plt # 设置页面标题 st.title("Students Information") # 读取CSV数据 stw = pd.read_csv("student_weight.csv") # 显示指标选择框 contact_options = ["Height", "Weight"] contact_selected = st.selectbox("Select an indicator to display", options=contact_options) # 根据选择生成折线图 fig, ax = plt.subplots() ax.plot(stw["Name"], stw[contact_selected]) ax.set_xlabel("Student Name") ax.set_ylabel(contact_selected) ax.set_title(f"Student {contact_selected} Distribution") # 旋转X轴标签避免名称重叠 plt.xticks(rotation=45) # 在Streamlit中渲染图表 st.pyplot(fig) # 显示选中指标的提示文本 st.write(f"Displaying result of {contact_selected}")
代码说明
- 调整逻辑顺序:先展示选择框,再根据用户选择动态生成图表
- 用matplotlib标准方式创建绘图对象,通过
st.pyplot()将图形输出到Streamlit页面 - 动态绑定选中指标与数据列,实现选择联动效果
- 添加坐标轴标签、标题,并旋转X轴标签优化可读性
- 移除原代码中无效的
st.line_chart错误调用
内容的提问来源于stack exchange,提问作者user18809841
相关产品推荐
相关产品推荐

