使用hist2d和不相等的bin来保存错误

时间:2018-01-17 12:02:40

标签: python matplotlib

我一直试图制作一个二维直方图,但是在savefig中一直出现错误。在hist2d中使用不等大小的bin时,似乎只会出现错误。 有没有人有任何见解?

这是一个复制错误的简单代码:

import matplotlib.pyplot as plt
import numpy as np

# This works...
fig1, ax1 = plt.subplots(figsize=(8,5))
x = np.random.randn(100000)
y = np.random.randn(100000)+5
h=ax1.hist2d(x,y,bins=([0,1,2,3],(2,3,4,5,6)))
fig1.savefig('test.pdf', bbox_inches='tight')
plt.close()

# This fails...(note unequal bin sizes)
fig1, ax1 = plt.subplots(figsize=(8,5))
x = np.random.randn(100000)
y = np.random.randn(100000)+5
h=ax1.hist2d(x,y,bins=([0,1,2,3],(2,3,5,6)))
fig1.savefig('test2.pdf', bbox_inches='tight')
plt.close()

我得到的错误信息在这里:

Traceback (most recent call last):
  File "unequal_bins.py", line 15, in <module>
    fig1.savefig('test.pdf', bbox_inches='tight')
  File "/Users/earpwl/anaconda/lib/python3.5/site-packages/matplotlib/figure.py", line 1573, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "/Users/earpwl/anaconda/lib/python3.5/site-packages/matplotlib/backend_bases.py", line 2210, in print_figure
    bbox = a.get_window_extent(renderer)
  File "/Users/earpwl/anaconda/lib/python3.5/site-packages/matplotlib/image.py", line 757, in get_window_extent
    x0, x1, y0, y1 = self._extent
TypeError: 'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:0)

这是一个known issue,其中matplotlib&lt; = 2.1.0。

解决方案是将bbox_inches='tight'参数省略为savefig,或者如该问题所述,添加

h[-1].set_extent(h[-1].get_extent())

完整的解决方案:

import matplotlib.pyplot as plt
import numpy as np

fig1, ax1 = plt.subplots()
x = np.random.randn(100000)
y = np.random.randn(100000)+5
h=ax1.hist2d(x,y,bins=[[0,1,2,3],[2,3,5,6]])

h[-1].set_extent(h[-1].get_extent())

fig1.savefig('test2.pdf', bbox_inches='tight')
plt.close()

将matplotlib更新到最新版本当然也是一种选择。 ; - )

相关问题