a button that creates and updates a plotly plot with a rectangle
Drop files here
or click to upload
import streamlit as st
import plotly.graph_objects as go
import numpy as np
# Initialize state for the rectangle dimensions
if 'width' not in st.session_state:
st.session_state.width = 1.0
st.session_state.height = 1.0
st.title("Interactive Rectangle Plot")
# Button to update the rectangle
if st.button("Update Rectangle"):
# Generate random dimensions between 0.5 and 2.0
st.session_state.width = np.random.uniform(0.5, 2.0)
st.session_state.height = np.random.uniform(0.5, 2.0)
# Create rectangle vertices
x = [0, st.session_state.width, st.session_state.width, 0, 0]
y = [0, 0, st.session_state.height, st.session_state.height, 0]
# Create the plot
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, fill="toself"))
# Update layout for better visualization
fig.update_layout(
showlegend=False,
width=600,
height=600,
xaxis=dict(range=[-0.5, 2.5]),
yaxis=dict(range=[-0.5, 2.5]),
title=f"Rectangle (Width: {st.session_state.width:.2f}, Height: {st.session_state.height:.2f})"
)
# Display the plot
st.plotly_chart(fig, use_container_width=True)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?