概况:
1、pymysql连接数据库
2、开启浮标,sql查询数据库某表数据
3、把查询的表数据放入dataframe格式,st.write打印出来,得到表格1
4、st.selectbox做选择框获取值传给option,得到选择效果2
5、获取饼图,先pd.value_counts对关键列表计数去重,得到新的表格后,
获取index作为标签 获取列data作为数据index=result.index.tolist() data=result.data.tolist()
matplotlib绘制饼图,用st.pyplot(fig)页面打出。
说明:
list表[a,b,c]
用print打印为[a,b,c]
用st.write打印为[0:a,1:b,2:c]
不必纠结,同样按照list处理即可
代码:
import matplotlib.pyplot as plt
import pymysql
import pandas as pd
import numpy as np
import seaborn as sns
import datetime
import streamlit as st
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
st.markdown('一, *信息表!* :sunglasses:')
#@st.cache(allow_output_mutation=True, hash_funcs={"_thread.RLock": lambda _: None})
#连接数据库
db = pymysql.connect(host='192.168.xx.xx',user='xxx',passwd='xxx',port=xxx,db='xxx')
#开启一个游标cursor
cursor=db.cursor()
#@st.cache(ttl=600)
#获取jifen_detail2020数据表里的所有数据
sql='select xxx,xxx,xxx,xxx,xxxfrom xxx;'
#执行sql中的语句
cursor.execute(sql)
st.write(cursor.description)
# 获得列名
column=[col[0] for col in cursor.description]
# 获得数据
data = cursor.fetchall()
# 获得DataFrame格式的数据
data_df=pd.DataFrame(list(data),columns=column)
st.write(data_df)
st.markdown('二, *信息表过滤选择效果!* :sunglasses::sunglasses:')
#用选择框作为选项
option = st.selectbox('Which company do you choose?', data_df['company_name'])
'You selected: ', option
#过滤选择后的结果
new_df1=data_df.loc[data_df["xxx"]==option]
st.write(new_df1)
st.markdown('三, *信息表在xxx占比!* :sunglasses::sunglasses::sunglasses:')
labelslist=list(data_df['xxx'])
result = pd.value_counts(labelslist)
index=result.index.tolist()
data=result.data.tolist()
labels = index
sizes = data
fig = plt.figure()
plt.pie(sizes, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)#'%1.1f':指小数点后保留一位有效数值;'%1.2f%%'保留两位小数点,增加百分号(%);startangle=90则从y轴正方向画起
plt.axis('equal')#该行代码使饼图长宽相等
plt.title('公司占比', fontdict={'size':15})
plt.legend(loc="upper right",fontsize=10,bbox_to_anchor=(1.1,1.05),borderaxespad=0.3)#添加图例
st.pyplot(fig)
运行后:


本文介绍了如何利用Python的pymysql库连接MySQL数据库,通过SQL查询获取数据,并将数据转换为dataframe。接着,利用Streamlit的st.selectbox创建选择框,实现用户交互。然后,通过value_counts对数据进行计数,生成饼图所需的数据,最后用matplotlib绘制饼图并使用st.pyplot在Streamlit应用中展示。整个过程展示了如何结合数据库操作、数据分析和交互式可视化。

727

被折叠的 条评论
为什么被折叠?



