如何使用python在streamlit和plotly中创建列?
Posted
技术标签:
【中文标题】如何使用python在streamlit和plotly中创建列?【英文标题】:how to create columns in streamlit and plotly with python? 【发布时间】:2021-07-20 13:12:47 【问题描述】:我正在使用新的数据科学网络应用 streamlit 创建一个仪表板,并与 plotly 协调。
在 streamlit 中,可以通过使用列分隔组件来创建 网格布局,您可以根据需要调整列的大小,使用以下语句:col1,col2,col3 = st.beta_columns(3)
问题是当我尝试这个选项时,图表会像这样显示在彼此上:
必须在条形图旁边显示饼图的位置
代码:
#Streamlit pckgs
import streamlit as st
# EDA pckgs
import pandas as pd
import numpy as np
#VIZ pckgs
import plotly.express as px
import plotly.graph_objs as go
col1,col2,col3 = st.beta_columns([2,2,2])
data = st.file_uploader("Upload Dataset",type=["csv","xlsx","xls"])
if data is not None:
#check the type of the file
if data.type =="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
df=pd.read_excel(data)
elif data.type =="application/vnd.ms-excel":
df=pd.read_csv(data)
all_columns_names = df.columns.tolist()
col = st.selectbox("Choose Column",df.columns.tolist())
selected_column_names__pyplot = st.multiselect("Select Columns",all_columns_names)
plot_btn = st.button("Generate Plot")
#count plot
with col1:
#pie chart
if st.checkbox("Pie Plot"):
if plot_btn:
data_pie = df[col].value_counts().to_frame()
labels=data_pie.index.tolist()
datavals=data_pie[col].tolist()
trace=go.Pie(labels=labels,
values=datavals,
hovertemplate = "%label: <br>Value: %value ",
showlegend=True,
textposition='inside',
)
layout = go.Layout(
title = 'Percentage of '.format(col),
height=600,
margin=go.Margin(l=0, r=200, b=100, t=100, pad=4) # Margins - Left, Right, Top Bottom, Padding
)
data = [trace]
fig = go.Figure(data=data,layout = layout)
st.plotly_chart(fig)
with col2:
if st.checkbox("Count_plot"):
# all_columns_names = df.columns.tolist()
# s=df[all_columns_names[0]].str.strip().value_counts()
if plot_btn:
s=df[col].str.strip().value_counts()
trace = go.Bar(
x=s.index,
y=s.values,
showlegend = True
)
layout = go.Layout(
title = 'Count of '.format(col),
)
data = [trace]
fig = go.Figure(data=data,layout = layout)
st.plotly_chart(fig)
基于----的答案,我将这一行st.plotly_chart(fig)
更改为这一行st.plotly_chart(fig, use_container_width=True)
但是图表变得非常小:
饼图在第一列的位置 条形图在第二列
【问题讨论】:
【参考方案1】:绘图时使用use_container_width=True
st.plotly_chart(fig, use_container_width=True)
【讨论】:
我试过你的答案,但它使图表非常小,我将编辑我的问题并显示结果 尝试使用 fig.update_layout(width=600,height=600) 结合上述更改来更新图形的宽度/高度以上是关于如何使用python在streamlit和plotly中创建列?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 plotly 和 streamlit 绘制 groupby
Python数据分析师使用低代码Streamlit实现Web数据可视化方法——Plotly可视化基础篇
如何让 Plotly 根据 Streamlit 应用程序中的屏幕分辨率调整绘图大小?