Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stevenferrer/3b62df680941f63773f918ddde9992cc to your computer and use it in GitHub Desktop.
Save stevenferrer/3b62df680941f63773f918ddde9992cc to your computer and use it in GitHub Desktop.
Interactive circle transformation via matrix multiplication
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
fig.tight_layout()
ax.set_aspect('equal', adjustable='box')
ax.set_frame_on(False)
# Cirlce matrix with 2x100 shape
theta = np.linspace(0, 3 * np.pi, 120)
radius = 32
# Plot the circle
def plot_circle(c, style='.'):
ax.plot(c[:, 0], c[:, 1], style)
c = np.stack((radius * np.cos(theta), radius*np.sin(theta))).T
plot_circle(c)
# Set min and max slider vals
val_min = -32
val_max = 32
# Make room for slider
plt.subplots_adjust(bottom=0.35)
# Make sliders
ax_x1 = plt.axes([0.25, 0.2, 0.65, 0.03])
x1_slider = Slider(
ax=ax_x1,
label="x1",
valmin=val_min,
valmax=val_max,
valinit=1,
)
ax_y1 = plt.axes([0.25, 0.15, 0.65, 0.03])
y1_slider = Slider(
ax=ax_y1,
label="y1",
valmin=val_min,
valmax=val_max,
valinit=0,
)
ax_x2 = plt.axes([0.25, 0.1, 0.65, 0.03])
x2_slider = Slider(
ax=ax_x2,
label="x2",
valmin=val_min,
valmax=val_max,
valinit=0,
)
ax_y2 = plt.axes([0.25, 0.05, 0.65, 0.03])
y2_slider = Slider(
ax=ax_y2,
label="y2",
valmin=val_min,
valmax=val_max,
valinit=1,
)
def on_changed(val):
T = np.array([
[x1_slider.val, y1_slider.val],
[x2_slider.val, y2_slider.val],
])
c = np.stack((radius * np.cos(theta), radius*np.sin(theta))).T
cT = c@T
ax.clear()
plot_circle(c, '-')
plot_circle(cT, 'g+')
x1_slider.on_changed(on_changed)
y1_slider.on_changed(on_changed)
x2_slider.on_changed(on_changed)
y2_slider.on_changed(on_changed)
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment