我正在用 Python v3.7.9 编写一些质谱数据缩减软件,并使用 matplotlib v3.5.3 来显示数据。
我最近发现我使用了错误的模块,matplotlib.pyplot
它与 tkinter 不兼容。我现在尝试切换到 using matplotlib.figure
,这是兼容的(参考)。
这导致了几个问题:
- 现在布局更加紧凑,导致轴几乎重叠,并且绘图周围有大量空白。
- 我无法添加副标题 (
AttributeError: module 'matplotlib.figure' has no attribute 'suptitle'
),即使matplotlib 文档中明确定义了该属性。
以下是一些前后的屏幕截图:第一个使用matplotlib.pyplot
紧凑布局,第二个使用matplotlib.figure
默认布局选项。
手动将布局设置为“紧密”或“约束”似乎根本没有太大效果,也不定义布局样式。
有没有一种方法可以恢复以前的“扩展”布局样式,而无需手动定义大量参数?
这是一个可以使用的示例脚本:
import customtkinter as ctk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.figure as Figure
# create the window using CTK
window = ctk.CTk()
# create the plot of random data
figure = Figure.Figure(figsize=(15,9))
Figure.layout = 'tight'
# create the subplots
ax1 = figure.add_subplot(2, 3, 1)
ax2 = figure.add_subplot(2, 3, 2)
ax3 = figure.add_subplot(2, 3, 3)
ax4 = figure.add_subplot(2, 3, 4)
ax5 = figure.add_subplot(2, 3, 5)
ax6 = figure.add_subplot(2, 3, 6)
# plot data in each subplot
data = [1, 2, 3, 4, 5]
ax1.plot(data)
ax2.plot(data)
ax3.plot(data)
ax4.plot(data)
ax5.plot(data)
ax6.plot(data)
# add titles to each subplot
ax1.set_title('Subplot 1')
ax2.set_title('Subplot 2')
ax3.set_title('Subplot 3')
ax4.set_title('Subplot 4')
ax5.set_title('Subplot 5')
ax6.set_title('Subplot 6')
# Add the plot to the window
canvas = FigureCanvasTkAgg(figure, master=window)
canvas.draw()
canvas.get_tk_widget().pack(side='top', fill='both', expand=True)
exit_button = ctk.CTkButton(window, text='Exit', command=window.destroy)
exit_button.pack(side='bottom') # add the exit button to the window
window.mainloop()
最后,正如我上面提到的,matplotlib 文档清楚地显示了一个.suptitle()
属性,但是,将Figure.suptitle('Data')
结果添加到AttributeError: module 'matplotlib.figure' has no attribute 'suptitle'
.我究竟做错了什么?
先感谢您!
如果您使用更标准的命名约定,一切可能不会那么混乱。
Figure
通常命名为fig
。您可以在实例化图形时设置布局
suptitle
是图形实例上的方法将其放在一起:
我明白了: