我希望将鼠标悬停在图上,并在自动生成的图窗口中导航栏的右侧获得干净的数据读取。
对于我来说(请参阅底部的代码),但是,如果我将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()
我想知道我做错了什么。我的猜测是,当滴答被砍掉(我的方式)时,根本不会读取任何信息。如果是这样,那真是遗憾,因为我只修改了滴答而不是数据。
答案 0 :(得分:3)
很明显,当您手动设置刻度标签时,无法显示有用的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()