我之前使用此代码制作了一些绘图,但由于某种原因,该代码向我抛出了一个错误。我以为我打错了,但事实并非如此。
#%%
import random
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import rc
nice = ['#899477', '#4da1a9', '#e59500','#7f99b1', '#7d4559',]
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
import numpy as np
r1 = random.sample(range(12), 5)
r2 = random.sample(range(13), 5)
r3 = random.sample(range(14), 5)
r4 = random.sample(range(15), 5)
#%%
df1 = pd.DataFrame({'location':[1,2,3,4,5], 'bar1':r2, 'bar2':r3})
df2 = pd.DataFrame({'location':[2,4,1,1,1], 'bar3':r4, 'bar1':r1})
#%%
d1 = dict(tuple(df1.groupby('location')))
d2 = dict(tuple(df2.groupby('location')))
#%%
for k, v in d1.items():
for k2, v2 in d2.items():
with PdfPages(r'{} Example.pdf'.format(k)) as pdf:
fig = plt.figure(figsize = (8,10.5))
gs=GridSpec(3,2) # 2 rows, 3 columns
ax1 = fig.add_subplot(gs[0,:])
plt.sca(ax1)
plt.bar(x=np.arange(5), height = v['bar2'], color = nice)
pdf.savefig(fig)
if k == k2:
fig2 = plt.figure(figsize = (8,10.5))
gs=GridSpec(3,2)
ax2 = fig.add_subplot(gs[0,:])
plt.sca(ax2)
plt.barh(y=np.arange(len(v2.bar3)), width = v2['bar3'], color = nice)
plt.gcf()
pdf.savefig(fig2)
plt.show()
根据评论的建议,我尝试指定该数字,但现在它仅保存在我拥有的第一个 for 循环制作的最后一个 pdf 中。此外,将最后一张图更改为 seaborn 图只是为了尝试不同的东西