我的代码看起来像
ylst = [.1,.2,.3,.4,.5,.6,.7,.8]
xlst=["A","B","C","D","E","F","G","H"]
with PdfPages('probs.pdf') as pdf_pages:
for i in range(0,len(xlst), 2):
ax=sns.barplot(xlst[i:i+2], ylst[i:i+2])
ax.axes.set_title('Which name', fontsize=24,color="b",alpha=0.3)
ax.set_ylabel("Probability (%)",size = 17,color="r",alpha=0.5)
for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
pdf_pages.savefig()
我想要4个图,在2行2列矩阵中。也就是说,左上图应显示A
和B
,其值为.1和.2。然后,左下角或右上角的图表应显示C
和D
,其值为.3和.4。等等
但是,我得到的是:
我该如何解决这个问题?
答案 0 :(得分:1)
我已经测试过这是有效的:
import matplotlib.pyplot as plt, seaborn as sns
from matplotlib.backends.backend_pdf import PdfPages
ylst = [.1,.2,.3,.4,.5,.6,.7,.8]
xlst=["A","B","C","D","E","F","G","H"]
with PdfPages('probs.pdf') as pdf_pages:
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2)
list_of_axes = (ax1,ax2,ax3,ax4)
for i,j in zip(range(0,len(xlst), 2),list_of_axes):
sns.barplot(xlst[i:i+2], ylst[i:i+2],ax=j)
j.axes.set_title('Which name', fontsize=24,color="b",alpha=0.3)
j.set_ylabel("Probability (%)",size = 17,color="r",alpha=0.5)
for p in j.patches:
j.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
pdf_pages.savefig()
plt.close()
我刚刚为每个子图分配了一个轴,并将.savefig()
移到了循环之外。