【问题标题】:Pyplot grid is not shown if I add Button widget如果我添加 Button 小部件,则不显示 Pyplot 网格
【发布时间】:2021-06-21 13:46:59
【问题描述】:

我有以下代码。网格在没有 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()

【问题讨论】:

    标签: python python-3.x matplotlib matplotlib-widget


    【解决方案1】:

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

    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 按钮的更多信息,请阅读并查看 sn-p:https://matplotlib.org/stable/gallery/widgets/buttons.html

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

    【讨论】:

      【解决方案2】:

      Button() 实例更改当前坐标区。所以当我调用plot.grid() 时,它是在按钮轴上操作的。我更改了调用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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 2022-01-03
        相关资源
        最近更新 更多