real-time data visualization
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
import time
# Set page config
st.set_page_config(
page_title="Real-Time Data Visualization",
page_icon="📊",
layout="wide"
)
# Initialize session state for data storage
if 'data' not in st.session_state:
st.session_state.data = pd.DataFrame(
columns=['timestamp', 'value1', 'value2', 'value3']
)
st.title("Real-Time Data Visualization 📊")
# Control panel
st.sidebar.header("Control Panel")
update_speed = st.sidebar.slider(
"Update Speed (seconds)",
min_value=1,
max_value=10,
value=2
)
# Function to generate random data
def generate_data():
return pd.DataFrame({
'timestamp': [pd.Timestamp.now()],
'value1': [np.random.normal(100, 10)],
'value2': [np.random.normal(50, 15)],
'value3': [np.random.normal(75, 20)]
})
# Create placeholder for charts
chart_cols = st.columns(2)
with chart_cols[0]:
line_chart_container = st.empty()
with chart_cols[1]:
area_chart_container = st.empty()
metrics_cols = st.columns(3)
# Main loop
if st.sidebar.button("Start Visualization"):
try:
while True:
# Generate new data
new_data = generate_data()
# Append to existing data
st.session_state.data = pd.concat(
[st.session_state.data, new_data],
ignore_index=True
)
# Keep only last 50 records
if len(st.session_state.data) > 50:
st.session_state.data = st.session_state.data.tail(50)
# Update metrics
with metrics_cols[0]:
st.metric(
"Value 1",
f"{st.session_state.data['value1'].iloc[-1]:.2f}",
f"{st.session_state.data['value1'].diff().iloc[-1]:.2f}"
)
with metrics_cols[1]:
st.metric(
"Value 2",
f"{st.session_state.data['value2'].iloc[-1]:.2f}",
f"{st.session_state.data['value2'].diff().iloc[-1]:.2f}"
)
with metrics_cols[2]:
st.metric(
"Value 3",
f"{st.session_state.data['value3'].iloc[-1]:.2f}",
f"{st.session_state.data['value3'].diff().iloc[-1]:.2f}"
)
# Update charts
line_chart_container.line_chart(
st.session_state.data.set_index('timestamp')[['value1', 'value2', 'value3']]
)
area_chart_container.area_chart(
st.session_state.data.set_index('timestamp')[['value1', 'value2', 'value3']]
)
# Wait before next update
time.sleep(update_speed)
except Exception as e:
st.error(f"Error occurred: {e}")
else:
st.info("Click 'Start Visualization' in the sidebar to begin the real-time visualization.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?