如何在Streamlit中创建基于选定指标的排行榜图表?
问题:使用Python和Streamlit创建基于指标的排行榜图表
我是Python和Streamlit新手,尝试创建一个排行榜。我的DataFrame样式如图所示,希望生成一个基于所选指标对最佳结果进行排名的图表,预期样式如图。
现有代码如下:
df=pd.read_csv('forcedecks-test-export-04_05_2023.csv', parse_dates=["Date"]) sb_options = list(df.columns) colselect1,colselect2 = st.columns(2) with colselect1: metric=st.selectbox('Select the Metric', options=sb_options) plot_assym = px.bar(df, x=metric.max(), y=df['Name'],template="plotly_white")
解决方案
关键问题修正
- 原代码中
px.bar的x=metric.max()错误:metric是选中的列名字符串,无法直接调用max(),应使用df[metric]获取对应列数据 - 未对数据按指标排序,图表无法体现排名逻辑
- 未处理非数值型列(如日期、文本),用户选择后会报错
修正后完整代码
import pandas as pd import streamlit as st import plotly.express as px # 读取数据 df = pd.read_csv('forcedecks-test-export-04_05_2023.csv', parse_dates=["Date"]) # 仅保留数值型列作为可选指标,避免无效选择 sb_options = [col for col in df.columns if pd.api.types.is_numeric_dtype(df[col])] # 布局:指标选择与排序方向设置 colselect1, colselect2 = st.columns(2) with colselect1: metric = st.selectbox('选择指标', options=sb_options) sort_direction = st.radio("排序方向", ["从高到低(最佳在前)", "从低到高"]) # 按选中指标排序并生成排名列 if sort_direction == "从高到低(最佳在前)": sorted_df = df.sort_values(by=metric, ascending=False).reset_index(drop=True) else: sorted_df = df.sort_values(by=metric, ascending=True).reset_index(drop=True) sorted_df["排名"] = sorted_df.index + 1 # 排名从1开始 # 生成横向条形排行榜 plot_assym = px.bar( sorted_df, x=metric, y="Name", color=metric, # 可选:按指标值着色,增强视觉区分 text="排名", # 在条形旁显示排名 template="plotly_white", orientation="h" # 横向布局更贴合排行榜阅读习惯 ) # 固定Y轴顺序,避免Plotly自动重排 plot_assym.update_layout( yaxis={ 'categoryorder': 'total ascending' if sort_direction == "从低到高" else 'total descending' } ) # 调整排名文本位置,避免被条形遮挡 plot_assym.update_traces(textposition='outside') # 在Streamlit中渲染图表 st.plotly_chart(plot_assym)
功能说明
- 自动过滤非数值型指标,确保选择有效性
- 支持双向排序,满足不同场景的排名需求
- 新增排名列并在图表中显示,直观体现名次
- 横向条形布局优化排行榜的可读性
- 固定轴顺序,保证排序逻辑与图表展示一致
内容的提问来源于stack exchange,提问作者Markus Fürst
相关产品推荐
相关产品推荐

