a button to create a rectangle shape on the selected area of a pyplot plot
To upload files, please first save the app
import streamlit as st
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
# Initialize session state to store rectangles
if 'rectangles' not in st.session_state:
st.session_state.rectangles = []
# Create a sample plot
fig, ax = plt.subplots()
# Plot some sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y)
# Add existing rectangles
for rect in st.session_state.rectangles:
ax.add_patch(rect)
# Button to add rectangle
if st.button("Add Rectangle", help="Click to add a rectangle. Use matplotlib's rectangle selector."):
# Create a rectangle (this is just a sample - in real interactive apps you'd use mouse events)
# For this example, we'll just add a rectangle at a fixed position
rect = patches.Rectangle((2, -0.5), 2, 1, linewidth=1, edgecolor='r', facecolor='none')
st.session_state.rectangles.append(rect)
ax.add_patch(rect)
st.experimental_rerun()
# Display the plot
st.pyplot(fig)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?