Streamlit Excel Line Chart: Create Two Line Charts Using Different Columns
Here is a sample code that allows the user to select a workbook and worksheet from their local directory, and then plots two line charts using different columns:
import streamlit as st
import pandas as pd
import altair as alt
# Function to read Excel file and return selected worksheet
def read_excel(file_path):
sheets = pd.read_excel(file_path, sheet_name=None)
sheet_names = list(sheets.keys())
selected_sheet = st.selectbox('Select a worksheet', sheet_names)
return sheets[selected_sheet]
# Main function
def main():
# Title and file upload
st.title('Excel Line Chart')
uploaded_file = st.file_uploader('Choose an Excel file', type=['xlsx'])
if uploaded_file is not None:
# Read Excel file and display worksheet selection
file = pd.ExcelFile(uploaded_file)
sheet = read_excel(uploaded_file)
# Display column selection for line chart 1
st.subheader('Line Chart 1')
col1 = st.selectbox('Select column for x-axis', sheet.columns)
col2 = st.selectbox('Select column for y-axis', sheet.columns)
# Display column selection for line chart 2
st.subheader('Line Chart 2')
col3 = st.selectbox('Select column for x-axis', sheet.columns)
col4 = st.selectbox('Select column for y-axis', sheet.columns)
# Create line chart 1
chart1 = alt.Chart(sheet).mark_line().encode(
x=col1,
y=col2
).properties(
width=600,
height=400,
title='Line Chart 1'
)
# Create line chart 2
chart2 = alt.Chart(sheet).mark_line().encode(
x=col3,
y=col4
).properties(
width=600,
height=400,
title='Line Chart 2'
)
# Display line charts
st.altair_chart(chart1)
st.altair_chart(chart2)
if __name__ == '__main__':
main()
The code uses the read_excel() function to read the selected worksheet from the uploaded Excel file. It then uses Streamlit's selectbox() function to allow the user to choose the columns for the x-axis and y-axis of each line chart. Finally, it uses Altair to create the line charts and Streamlit's altair_chart() function to display them.
原文地址: https://www.cveoy.top/t/topic/n5Q9 著作权归作者所有。请勿转载和采集!