如何使用matplotlib与图紧密布局? [英] How to use matplotlib tight layout with Figure?
问题描述
我找到了pyplot的ightt_layout函数,并希望使用它.在我的应用程序中,我将matplotlib图嵌入到Qt GUI中,并使用Figure而不是pyplot.有什么办法可以在我那里应用tight_layout吗?如果我在一个图形中有多个轴,也可以使用吗?
I found tight_layout function for pyplot and want to use it. In my application I embed matplotlib plots into Qt GUI and use figure and not pyplot. Is there any way I can apply tight_layout there? Would it also work if I have several axes in one figure?
推荐答案
只需像往常一样调用fig.tight_layout()
. (pyplot
只是一个方便包装器.在大多数情况下,您仅使用它来快速生成图形和轴对象,然后直接调用其方法.)
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
QtAgg
后端和默认后端之间应该没有区别(或者,如果有,那就是一个错误).
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
例如
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()
这篇关于如何使用matplotlib与图紧密布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!