Matplotlib Python: How to add panel button

2020-08-02 01:36发布

问题:

I am using matplotlib to create a simple interactive plot where the user will be able to place markers on the plot. For that matter everything works fine.

Now I want to add a button that when pressed a certain function will be executed. For that I followed that example. But using the button causes unexpected behavior. With the button included instead of being able to add markers all markers are placed inside the button area and are not displayed at all in the graph. Which doesn't make much sense.

I am looking for a way to add a panel button like those that exist by default in every matplotlib window. Do you have any suggestion? Any other example that I could take a look into? I have seen a lot of examples but I find to it hard to navigate through the documentation to find exactly what I need. Thanks in advance.

update

The code I use right now looks like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

dataX = np.array([1,2,3,4,5,6,7,8,9,10])
dataY = np.array([1193,1225,1125,1644,1255,13676,2007,2008,12359,1210])

def on_click(event):
    if event.dblclick:
        plt.plot((event.xdata, event.xdata),(mean-standardDeviation, mean+standardDeviation), 'r-')
        plt.show()

def _yes(event):
    print "yolo"

global mean, standardDeviation

# mean and standard deviation
mean = np.mean(dataY)
standardDeviation = np.std(dataY)

# plot data
plt.plot(dataX, dataY, linewidth=0.5)

plt.connect('button_press_event', on_click)

# button
axcut = plt.axes([0.9, 0.0, 0.1, 0.075])
bcut = Button(axcut, 'YES', color='red', hovercolor='green')
bcut.on_clicked(_yes)

plt.show()

When the button is not added everything works as expected. With the button I can only place markers inside the button's area. Any idea?

回答1:

You need to separate those two.

Let's try with subplot:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

dataX = np.array([1,2,3,4,5,6,7,8,9,10])
dataY = np.array([1193,1225,1125,1644,1255,13676,2007,2008,12359,1210])

ax = plt.subplot(111)
def on_click(event):
    if event.dblclick:
       ax.plot((event.xdata, event.xdata), (mean-standardDeviation, mean+standardDeviation), 'r-')
       plt.show()

def _yes(event):
    print("yolo")

mean = np.mean(dataY)
standardDeviation = np.std(dataY)

ax.plot(dataX, dataY, linewidth=0.5)
plt.connect('button_press_event', on_click)

axcut = plt.axes([0.9, 0.0, 0.1, 0.075])
bcut = Button(axcut, 'YES', color='red', hovercolor='green')
bcut.on_clicked(_yes)

plt.show()

Now it should work.

But, if you accidentally double click on yes it will draw a line on a graph. So, if you change button action to right-click:

def _yes(event):
    if event.button == 3:
        print("yolo")

Now it's fine :)