【发布时间】:2012-03-25 02:01:21
【问题描述】:
我找到了 pyplot 的 tight_layout 函数并想使用它。在我的应用程序中,我将 matplotlib 绘图嵌入到 Qt GUI 中并使用图而不是 pyplot。有什么方法可以在那里申请tight_layout 吗?如果我在一个图中有多个轴,它也可以工作吗?
【问题讨论】:
标签: python matplotlib figure
我找到了 pyplot 的 tight_layout 函数并想使用它。在我的应用程序中,我将 matplotlib 绘图嵌入到 Qt GUI 中并使用图而不是 pyplot。有什么方法可以在那里申请tight_layout 吗?如果我在一个图中有多个轴,它也可以工作吗?
【问题讨论】:
标签: python matplotlib figure
只需像往常一样拨打fig.tight_layout()。 (pyplot 只是一个方便的包装器。在大多数情况下,您只是使用它来快速生成图形和轴对象,然后直接调用它们的方法。)
QtAgg 后端和默认后端之间应该没有区别(或者如果有,那是一个错误)。
例如
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
【讨论】:
pyplot.figure() ax 对象的 mpl_toolkits.basmap 一起使用时,我得到了 ValueError: max() arg is an empty sequence。这是一个错误,还是一起使用这个和basemap 的限制?
cartopy 以获得更现代的 matplotlib 映射工具包。)
tight_layout 所做的只是计算 subplots_adjust 的参数,因此 tight_layout 仅适用于子图。使用fig, ax = plt.subplots() 或ax = fig.add_subplot(1,1,1) 而不是手动指定轴的范围,它应该可以正常工作。 (顺便说一下,在这种情况下,较新版本的 matplotlib 会给出更多信息错误。)
fig = Figure() 建议将导致tight_layout 提高ValueError,除非以其他方式实例化轴。 subplots 是创建坐标轴和图形实例的正确方法。