user1054158
user1054158

Reputation:

Interacting with matplotlib

The code above draws a basic grid. I would like to do the following things.

  1. Know where the user clicks on the draw so as to change the face color of a rectangle. The problem is to know that the user has clicked and then to have the coordinates of the click. Is it possible ?
  2. I would like also to interact with key events. For example, if the space key is activated, I would like to go back to the initial draw. The problem is to know that a key has been pressed, and to have the ascii code of this key. Is it possible ?

MY STARTING CODE

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

Answers (1)

user1054158
user1054158

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

Related Questions