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

如何用Streamlit和Python基于多列气象数据生成折线图

解决Streamlit气象数据折线图展示问题

问题概述

需要基于Streamlit和Python处理包含time、temperature、pressure等列的气象CSV数据,实现以下功能:

  • 选择日期范围
  • 多选temperature至P3的数据集并在同一折线图中展示

已完成文件上传、日期筛选、侧边栏数据集多选功能,但无法生成对应筛选条件的折线图,也不清楚如何在同一图表展示多列数据。

完整修正代码

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

st.set_page_config(
    page_title='Real-Time Data Weather Dashboard',
    page_icon='🌤️',
    layout='wide'
)

st.title(" :bar_chart: Real-Time / Weather Data from Enviro+")
st.markdown('<style>div.block-container{padding-top:1rem;}</style>', unsafe_allow_html=True)

# 文件上传或加载本地数据
fl = st.file_uploader(":file_folder: Upload a file", type=("csv", "txt", "xlsx", "xls"))
if fl is not None:
    filename = fl.name
    st.write(filename)
    df = pd.read_csv(fl, encoding="ISO-8859-1")
else:
    os.chdir(r"C:\WeatherData")
    df = pd.read_csv("WeatherData.csv", encoding="ISO-8859-1")

# 处理时间列
df["time"] = pd.to_datetime(df["time"])

# 日期范围筛选
col1, col2 = st.columns((2))
startDate = df["time"].min()
endDate = df["time"].max()

with col1:
    date1 = pd.to_datetime(st.date_input("Start Date", startDate))

with col2:
    date2 = pd.to_datetime(st.date_input("End Date", endDate))

# 应用日期筛选
filtered_df = df[(df["time"] >= date1) & (df["time"] <= date2)].copy()

# 侧边栏数据集选择
st.sidebar.header("Choose your filter: ")
# 可选数据集排除time列,只展示气象指标列
available_columns = [col for col in df.columns if col != "time"]
data_set = st.sidebar.multiselect("Pick your data set", available_columns, default=["temperature"])

# 准备绘图数据:保留time列和选中的数据集列
plot_df = filtered_df[["time"] + data_set]

# 生成折线图:x轴为time,y轴为选中的所有数据集列
fig = px.line(
    plot_df,
    x="time",
    y=data_set,
    height=500,
    template="gridon",
    title="Weather Data Trend"
)
st.plotly_chart(fig, use_container_width=True)

关键改进说明

  1. 修复文件读取逻辑:上传文件时直接使用文件对象读取,避免本地路径匹配问题
  2. 优化数据集选择:
    • 排除time列,仅展示气象指标作为可选数据集
    • 设置默认选中temperature列,满足未选择时的默认展示需求
  3. 正确准备绘图数据:明确保留time列作为x轴数据源,仅将选中的指标列作为y轴数据
  4. 多列数据同图展示:Plotly Express的px.line支持直接传入多列作为y参数,自动生成多条折线并添加图例,实现同一图表展示多维度数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:33:00