Python:无法使用PdfPages将matplotlib hist2d plot保存到文件

Python:无法使用PdfPages将matplotlib hist2d plot保存到文件,python,matplotlib,plot,histogram,Python,Matplotlib,Plot,Histogram,我正在尝试将使用生成的多个2D直方图保存到使用以下代码生成的多页pdf: import numpy as np import pandas as pd import seaborn as sns import scipy.stats as stats import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import warnings import subprocess impo

我正在尝试将使用生成的多个2D直方图保存到使用以下代码生成的多页pdf:

import numpy as np
import pandas as pd
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import warnings 
import subprocess
import os
warnings.simplefilter("ignore", category=PendingDeprecationWarning)

x1 = np.random.randn(100000)
y1 = np.random.randn(100000) + 5

pp = PdfPages("somepdf.pdf")
fig = plt.figure()
plt.hist2d(x=x1,y=y2, bins=50)
plt.title(row['smRNAname'])
plt.xlabel("Position(BP)")
plt.ylabel("Read Length")
cb = plt.colorbar()
cb.set_label('counts in bin')
pp.savefig(fig, dpi=300, transparent = True)
plt.close()

fig = plt.figure()
fig = plt.hist2d(x=x1,y=y1, bins=50)
plt.title(row['PIWIname'])
plt.xlabel("Position(BP)")
plt.ylabel("Read Length")
cb = plt.colorbar()
cb.set_label('counts in bin')
pp.savefig(fig, dpi=300, transparent = True)
plt.close()
pp.close()
但我得到了以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-ccbb61958687> in <module>()
     61     cb = plt.colorbar()
     62     cb.set_label('counts in bin')
---> 63     pp.savefig(fig, dpi=300, transparent = True)
     64     plt.close()
     65 

/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_pdf.py in savefig(self, figure, **kwargs)
   2519                 manager = Gcf.get_active()
   2520             else:
-> 2521                 manager = Gcf.get_fig_manager(figure)
   2522             if manager is None:
   2523                 raise ValueError("No figure {}".format(figure))

/anaconda3/lib/python3.7/site-packages/matplotlib/_pylab_helpers.py in get_fig_manager(cls, num)
     39         figure and return the manager; otherwise return *None*.
     40         """
---> 41         manager = cls.figs.get(num, None)
     42         if manager is not None:
     43             cls.set_active(manager)

TypeError: unhashable type: 'numpy.ndarray'
从错误本身来看,我可以理解这可能是因为hist2d返回一个2D数组,而不是引用图形。
直接使用plt.savefigtest.pdf保存直方图效果很好。我不确定我做错了什么,或者这是不可能的?

我认为问题在于:

fig = plt.figure()
fig = plt.hist2d(x=x1,y=y1, bins=50) <---- here should be plt.hist2d(x=x1,y=y1, bins=50)
plt.title(row['PIWIname'])

让我知道它是否有效:

谢谢您的回复,但我担心问题仍然存在。我猜hist2d返回了一些非规范的东西?是的,但不应该覆盖fig对象。你确定它不起作用吗?您正在绘制两个图形。第一个会被绘制,第二个不会。并检查两个图之间的差异。在第一个示例中,您没有错误地指定fig对象。hist2d返回什么并不重要,但这里重要的一点是它不会返回matplotlib.figure.figure。因此,无论出于何种原因,如果你需要存储报税表,不要将其命名为fig或任何暗示它将是一个数字的东西。