【问题标题】:Matplotlib shows no reading if the tick labels get modified如果刻度标签被修改,Matplotlib 不会显示读数
【发布时间】:2019-05-09 23:18:49
【问题描述】:

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

然而,在我的例子中(见底部的代码),如果我将 y 轴刻度标签转换为分贝,导航栏(右下角)中的 y 读数将消失,如下所示:

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

我用来打包小部件的代码:

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

我想知道我哪里做错了。我的猜测是,当滴答声被黑客入侵(我的方式)时,根本不会有读数......如果是这样,那就太可惜了,因为我只修改了滴答声而不是数据。

【问题讨论】:

    标签: python matplotlib tkinter


    【解决方案1】:

    很明显,当您手动设置刻度标签时,无法显示有用的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()
    

    【讨论】:

    • 非常感谢!因此,正如我在发布后想到的那样,数据读取有一个回调。您的 Formatter 代码中只有一个问题,即修复: if x != 0: s = 20*np.log10(np.sign(x)*x) 。我已将其修复到位并将接受您的回答。
    • 我已经实现了您在问题中的确切代码。如果你想要求不同的东西,你可以这样做。我重新滚动了您的编辑。
    • "很明显,当您手动设置刻度标签时,不会显示任何有用的 y 坐标......" 虽然这可能是它的工作原理,但这并不十分明显,因为 xy 读数并不明显在底部的任务栏中依靠刻度。在看到这个答案之前,有人很容易想象他们只依赖数据本身。
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2020-03-27
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多