0

I have the following code. The grid is visible without the Button widget. But when the grid is not shown if I add the button. What am I doing wrong?

from matplotlib import pyplot as plot
from matplotlib.widgets import Button

plot.plot([1,2,3], [1,2,3])
ax = plot.axes([0.5, 0.5, 0.05, 0.05])
Button(ax, "A")
plot.grid()
plot.show()
Dinesh
  • 1,825
  • 5
  • 31
  • 40

2 Answers2

0

For me you code is working fine! (Except the button is in the middle of the screen) Maybe you should try the following snippet:

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

freqs = np.arange(2, 20, 3)

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = plt.plot(t, s, lw=2)


class Index:
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

callback = Index()
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()

To read more about matplotlib buttons read and see the snippet: https://matplotlib.org/stable/gallery/widgets/buttons.html

Also you might want to rename the button to have a bigger name like "TEST" to avoid problems regarding the size of the label.

Wrench56
  • 290
  • 2
  • 14
0

The Button() instantiation changes the current axes. So when I call plot.grid() it is operated on Button axes. I changed the order of calling plot.grid() and it worked. I have shown the modified code below.

from matplotlib import pyplot as plot
from matplotlib.widgets import Button

plot.plot([1,2,3], [1,2,3])
# note grid() is called before Button
plot.grid()

ax = plot.axes([0.5, 0.5, 0.05, 0.05])
Button(ax, "A", hovercolor="red")

plot.show()
Dinesh
  • 1,825
  • 5
  • 31
  • 40