Reputation:
The code above draws a basic grid. I would like to do the following things.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
n = 2**3
plt.axes(xlim = (0, n), ylim = (0, n))
plt.axis('off')
for line in range(n):
for col in range(n):
rect = mpatches.Rectangle(
(line, col), 1, 1,
facecolor = "white",
edgecolor = "black"
)
plt.gca().add_patch(rect)
plt.show()
Upvotes: 1
Views: 647
Reputation:
Here is a solution where the draw of the rectangle has not been factorized. Indeed matplotlib
gives a very easy to use interface for events.
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
n = 2**3
def drawInitial():
plt.axes(xlim = (0, n), ylim = (0, n))
plt.axis('off')
for line in range(n):
for col in range(n):
rect = mpatches.Rectangle(
(col, line), 1, 1,
facecolor = "white",
edgecolor = "black"
)
plt.gca().add_patch(rect)
def onclick(event):
col = int(event.xdata)
line = int(event.ydata)
rect = mpatches.Rectangle(
(col, line), 1, 1,
facecolor = "black",
edgecolor = "black"
)
plt.gca().add_patch(rect)
plt.draw()
def onkey(event):
if event.key == " ":
drawInitial()
plt.draw()
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('key_press_event', onkey)
drawInitial()
plt.show()
Upvotes: 2