如何通过允许用户使用 plotly 和 python with streamlit 选择列来绘制条形图

how to plot bar chart by allowing the user to choose the columns using plotly and python with streamlit

我有一个包含 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)

你需要使用

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

这导致: