【问题标题】:how to plot bar chart by allowing the user to choose the columns using plotly and python with streamlit如何通过允许用户使用 plotly 和 python with streamlit 选择列来绘制条形图
【发布时间】:2021-06-27 07:44:42
【问题描述】:

我有一个由 3 列组成的数据框 我想要的是根据用户对列的选择来绘制结果。

到目前为止,我能够绘制 条形图,但在代码中指定列而不是基于用户输入。

如果我尝试用户输入系统崩溃并显示以下错误:

AttributeError: 'DataFrame' object has no attribute 'str'

代码:

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

df =pd.DataFrame({"source_number":[11199,11328,11287,32345,12342,1232,13456,123244,1235],
    "location":["loc1","loc2","loc3","loc1","loc1","loc2","loc3","loc2","loc1"],
    "category":["cat1","cat3","cat1","cat3","cat2","cat3","cat2","cat3","cat1"],
    })

columns = df.columns.tolist()
selected_columns = st.multiselect("select column",columns)
s = df[selected_columns].str.strip().value_counts()

trace = go.Bar(x=s.index,y=s.values,showlegend = True)
layout = go.Layout(title = "test")
data = [trace]
fig = go.Figure(data=data,layout=layout)
st.plotly_chart(fig)

【问题讨论】:

    标签: python dataframe plotly streamlit


    【解决方案1】:

    你需要使用

    selected_columns = st.multiselect("select column", columns, default="location")
    s = df[selected_columns[0]].str.strip().value_counts()
    

    这会导致:

    【讨论】:

    • 如果我想为多列绘制分组结果怎么办?
    • @user5980666 如何处理source_number 值?还是您只想拥有locationcategory
    • 只想绘制位置和类别结果
    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 2020-02-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2021-07-20
    相关资源
    最近更新 更多