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

问题描述

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

               prices         Type
name
ResidenceA     [1.0,2.0]     Condo
ResidenceB     [2.0]          Apartment
ResidenceC     [3.0]          Mansion
ResidenceD     [4.0]          Mansion

解决方法

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

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.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,3])
# note grid() is called before Button
plot.grid()

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

plot.show()