如果我添加 Button 小部件,则不会显示 Pyplot 网格

Pyplot grid is not shown if I add Button widget

我有以下代码。网格在没有 Button 小部件的情况下可见。但是当我添加按钮时没有显示网格。我做错了什么?

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()

对我来说,你的代码工作正常! (除了按钮在屏幕中间) 也许您应该尝试以下代码段:

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()

要阅读有关 matplotlib 按钮的更多信息,请阅读并查看代码段:https://matplotlib.org/stable/gallery/widgets/buttons.html

此外,您可能希望将按钮重命名为更大的名称,例如“TEST”,以避免出现有关标签大小的问题。

Button() 实例化改变了当前轴。所以当我调用 plot.grid() 时,它是在 Button 轴上操作的。我更改了调用 plot.grid() 的顺序并且它起作用了。我在下面显示了修改后的代码。

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()