我想在一个只有一个图的图上使用matplotlib的tight_layout函数,但是它给了我一个AssertionError。这是我的代码:(注:更新w.r.t.原帖)
def plot_histogram_00():
fig, _ = plt.subplots(figsize=(9, 5))
fig.tight_layout()
fig.close()
当我在Windows 7计算机上运行Eclipse(Python 2.7,matplotlib 1.4)时,它运行正常,我得到了一个不错的输出。但是,当我在我的Mac计算机(也是Python 2.7,matplotlib 1.4)上运行完全相同的代码(从Dropbox文件夹运行)时,收到以下错误消息:
Traceback (most recent call last):
File "/Users/david/Dropbox/Sandbox/Histogram.py", line 139, in <module>
plot_histogram_00();
File "/Users/david/Dropbox/Sandbox/Histogram.py", line 38, in plot_histogram_00
fig.tight_layout()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 1654, in tight_layout
rect=rect)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/tight_layout.py", line 352, in get_tight_layout_figure
pad=pad, h_pad=h_pad, w_pad=w_pad)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/tight_layout.py", line 131, in auto_adjust_subplotpars
fig.transFigure.inverted())
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/matplotlib/transforms.py", line 1057, in __init__
assert isinstance(transform, Transform)
AssertionError
是否有人能指出我将开始寻找此错误原因的方向?
更新:我的原始代码是:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
def plot_histogram_00():
xlabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
np.random.seed(1)
values_A = np.random.choice(np.arange(len(xlabels)),
size=200, replace=True).tolist()
values_B = np.random.choice(np.arange(len(xlabels)),
size=200, replace=True).tolist()
fig, ax = plt.subplots(figsize=(9, 5))
_, bins, patches = plt.hist([values_A, values_B], normed=1,
bins=len(xlabels),
color=['#3782CC', '#AFD5FA'],
label=['A', 'B'])
fig.tight_layout()
plt.savefig('my_plot_00.png')
答案 0 :(得分:2)
对于使用由brew-python管理的matplotlib安装的mac,我遇到了同样的问题。通过在brew(brew uninstall --force matplotlib
)中完全删除它来修复它,然后删除/usr/local/lib/python2.7/site-packages
中剩余的源文件夹。从pip重新安装:pip install matplotlib
。
之前使用brew-python的主要原因是matplotlib没有标准的setup.py脚本。因为这似乎在matplotlib的最新安装中得到了修复,我想我现在可以完全依赖pip了。