代码之家  ›  专栏  ›  技术社区  ›  kakyo

如果勾号标签被修改,Matplotlib将不显示读数

  •  1
  • kakyo  · 技术社区  · 6 年前

    我希望将鼠标悬停在绘图上,并在自动生成的绘图窗口的导航栏右侧获得干净的数据读取。

    enter image description here

    解决方法:如果您注释掉 #PROBLEM 代码块,则右下角的y读数将可见,如下所示:

    enter image description here

    from os.path import abspath, dirname, join
    import tkinter as tk
    
    import numpy as np
    import matplotlib
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk as NavigationToolbar
    from scipy.io import wavfile
    
    root = tk.Tk()
    mainframe = tk.Frame(root)
    mainframe.pack()
    
    frame = tk.Frame(mainframe)
    frame.pack()
    figFrame = tk.Frame(frame)
    toolFrame = tk.Frame(frame)
    figFrame.pack(side='top', fill='both', expand=True)
    toolFrame.pack(side='top', fill='both', expand=True)
    
    # Place the figure
    fig = plt.Figure()
    figWidget = FigureCanvasTkAgg(fig, master=figFrame)
    track = figWidget.get_tk_widget()
    track.pack(side='top', fill='both', expand=True)
    
    # Place the toolbar
    toolbar = NavigationToolbar(figWidget, toolFrame)
    toolbar.pack(side='top', fill='both', expand=True)
    
    # Get data
    SR, signal = wavfile.read(join(abspath(dirname(__file__)), 'y.wav'))
    
    # Plot the signal read from wav file
    ax = fig.add_subplot(111)
    ax.set_title('Waveform and Spectrogram of a wav file')
    ax.plot(signal)
    ax.set_xlabel('Sample')
    ax.set_ylabel('Amplitude')
    
    # PROBLEM: Truncated y-readings in Toolbar
    ax.set_ylabel('Amplitude (dB)')
    ticks = ax.get_yticks()
    t1 = 20*np.log10(-ticks[(ticks < 0)])
    t2 = 20*np.log10(ticks[(ticks > 0)])
    t1 = [float('{:.1f}'.format(i)) for i in t1]
    t2 = [float('{:.1f}'.format(i)) for i in t2]
    ticks = np.concatenate((t1, [-np.inf], t2))
    ax.set_yticklabels(ticks)
    # PROBLEM: END
    
    
    plt.show()
    
    root.mainloop()
    

    我不知道我哪里做错了。我的猜测是,当蜱虫被砍掉(我的方式),那么就不会有任何阅读了。。。。如果是这样的话,那就很遗憾了,因为我只修改了刻度,而没有修改数据。

    1 回复  |  直到 6 年前
        1
  •  4
  •   ImportanceOfBeingErnest    6 年前

    很明显,没有什么有用的 y 手动设置标签时可以显示坐标;如果你认为你可以标出情节的话,那也许就更清楚了。 "Apple", "Banana", "Cherry" -在这种情况下,当鼠标位于中间位置时,坐标是多少 "Banana" "Cherry"

    但是,您可以使用 FuncFormatter 设置勾选标签的格式。

    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter
    import numpy as np
    
    signal = np.sin(np.linspace(0,12,300))*.7
    
    
    fig, ax = plt.subplots()
    ax.set_title('Waveform and Spectrogram of a wav file')
    ax.plot(signal)
    ax.set_xlabel('Sample')
    ax.set_ylabel('Amplitude (dB)')
    
    def fmt(x,pos=None):
        if x==0:
            return "-inf"
        else:
            return '{:.1f}'.format(20*np.log10(np.sign(x)*x))
    
    ax.yaxis.set_major_formatter(FuncFormatter(fmt))
    
    
    plt.show()
    

    enter image description here