Skip to main content
 首页 » 编程设计

python之matplotlib 的 tight_layout() 中的 AssertionError

2024年10月25日10arxive

我想在只有一个图的图形上使用 matplotlib 的 tight_layout 函数,但它给了我一个 AssertionError。这是我的代码:(注意:更新 w.r.t. 原始帖子)

def plot_histogram_00():     
    fig, _ = plt.subplots(figsize=(9, 5))         
    fig.tight_layout() 
    fig.close() 

当我在我的 Windows 7 计算机(Python 2.7、matplotlib 1.4)上的 Eclipse 中运行它时,它运行良好,并且我得到了一个不错的输出。但是,当我在我的 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') 

请您参考如下方法:

我在使用 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。