Python Forum
How to create a new plot in a figure right below the first one after click event? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: How to create a new plot in a figure right below the first one after click event? (/thread-18478.html)



How to create a new plot in a figure right below the first one after click event? - codexx - May-19-2019

Given a matrix (list of lists)
    A = [[1, 2, 3],
         [4, 6, 8],
         [9, 12, 15]]

and a list
x = [1, 2, 3]
.

Each row j (0 <= j <= 2) of A consists of y-values so that 3 straight lines in total can be created in combination with x.

Now I want to plot these straight lines in the same plot with a special feature. If the user clicks on the graphic, an event handler should receive the x-position and create another plot right below the first one. This plot should be 1D and only visualise the data of the column in A whose index is given by the x-position.

Example: A click on x = 1 should plot [1 4 9], x = 2 should plot [2 6 12] and so on.


I have already tried to add a subplot using figure1.add_subplot(211) for the first plots and `figure1.add_subplot(212) within the event handler and it also did not work.

import matplotlib.pyplot as plt
A = [[1 2 3], [4 5 6], [7 8 9]]
x = [1 2 3]
figure1 = plt.figure()
plt.plot(x, A[0])
plt.plot(x, A[1])
plt.plot(x, A[2])

def onclick(event):
    Y = [A[i][int(event.xdata)] for i in range(0, 3)]
    plt.plot(Y)

figure1.canvas.mpl_connect('button_press_event', onclick)



Thanks in advance


RE: How to create a new plot in a figure right below the first one after click event? - heiner55 - May-26-2019

#!/usr/bin/python3
import matplotlib.pyplot as plt

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
x = [1, 2, 3]

figure1 = plt.figure()

plt.plot(x, A[0])
plt.plot(x, A[1])
plt.plot(x, A[2])

def onclick(event):
    if event.xdata == None:
        return
    col = int(event.xdata)
    if 0 <= col <= 2:
       Y = [A[i][col] for i in range(0, 3)]
       plt.figure()
       plt.plot(Y)
       plt.show()

figure1.canvas.mpl_connect('button_press_event', onclick)
plt.show()