我正在尝试使用以下代码将使用hist2d生成的多个2D直方图保存到使用PdfPages生成的多页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数组而不是引用fig(?)。 直接使用plt.savefig(“ test.pdf”)保存直方图就可以了。我不确定自己在做什么错,还是不可能?
答案 0 :(得分:1)
我相信问题出在此
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'])
让我知道它是否有效:)