使用Streamlit和Matplotlib創(chuàng)建交互式折線圖
本教程將介紹如何使用Streamlit和Matplotlib創(chuàng)建一個用戶友好的數(shù)據(jù)可視化Web應(yīng)用程序。該應(yīng)用程序允許上傳CSV文件,并為任何選定列生成折線圖。
圖片
構(gòu)建Streamlit應(yīng)用程序
在本文中,我們將指導(dǎo)你完成創(chuàng)建此應(yīng)用程序的步驟。無論你是專家還是剛剛?cè)腴T,最終你都能輕松地將Parquet文件轉(zhuǎn)換為可視化結(jié)果。所以,跟隨本教程開始吧。
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
def main():
st.set_page_config(page_title='Line Plotter', page_icnotallow=':chart_with_upwards_trend:')
st.title('Line Plotter')
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
圖片
然后,用戶從下拉列表中選擇要在折線圖中可視化的列。該應(yīng)用程序還提供了文本輸入字段,用于輸入繪圖的標(biāo)題以及X軸和Y軸的標(biāo)簽。顏色選擇器讓用戶選擇折線圖的顏色。
column = st.selectbox('Select a column', df.columns)
title = st.text_input('Title', 'Line Plot')
x_label = st.text_input('X-axis Label', 'X-axis')
y_label = st.text_input('Y-axis Label', 'Y-axis')
color = st.color_picker('Line Color', '#1f77b4')
圖片
使用Matplotlib創(chuàng)建折線圖
根據(jù)用戶的輸入,該應(yīng)用程序使用Matplotlib生成一條線圖,將選擇的列繪制在DataFrame的索引上。
X軸標(biāo)簽旋轉(zhuǎn)45度,以確保它們易于閱讀且不會重疊。
fig, ax = plt.subplots()
ax.plot(df.index, df[column], color=color)
ax.set_title(title)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
# Rotate X-axis labels
plt.xticks(rotatinotallow=45)
st.pyplot(fig)
if __name__ == '__main__':
main()
圖片
總結(jié)
這就是本文簡單的教程!使用Streamlit和Matplotlib創(chuàng)建的一個簡單的交互式數(shù)據(jù)可視化Web應(yīng)用程序。該應(yīng)用程序是一個很好的工具,可以快速將CSV文件中的不同數(shù)據(jù)列可視化為折線圖。通過提供用戶友好的控件,如下拉列表、文本字段和顏色選擇器,該應(yīng)用程序允許用戶輕松自定義其數(shù)據(jù)可視化。
雖然此應(yīng)用程序相當(dāng)簡單,但它展示了Streamlit和Matplotlib創(chuàng)建交互式、用戶友好的數(shù)據(jù)可視化應(yīng)用程序的強(qiáng)大功能。用戶可以隨意擴(kuò)展。