a button that adds a rectangle to a plotly figure in the session state
To upload files, please first save the app
import streamlit as st
import plotly.graph_objects as go
# Initialize the figure in session state if it doesn't exist
if "fig" not in st.session_state:
# Create an empty figure with a white background
st.session_state.fig = go.Figure()
st.session_state.fig.update_layout(
plot_bgcolor='white',
xaxis=dict(range=[0, 10]),
yaxis=dict(range=[0, 10])
)
# Initialize rectangle counter
if "rect_count" not in st.session_state:
st.session_state.rect_count = 0
# Button to add rectangle
if st.button("Add Rectangle", type="primary"):
# Calculate position based on count to avoid complete overlap
offset = st.session_state.rect_count % 5
# Add a rectangle shape
st.session_state.fig.add_shape(
type="rect",
x0=1 + offset,
y0=1 + offset,
x1=3 + offset,
y1=3 + offset,
line=dict(color="RoyalBlue"),
fillcolor="LightSkyBlue",
opacity=0.7,
)
st.session_state.rect_count += 1
# Display the figure
st.plotly_chart(st.session_state.fig, use_container_width=True)
# Show current count of rectangles
st.write(f"Number of rectangles: {st.session_state.rect_count}")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?