I have 2x2 gird. I want pie chart at position (0,0) (0, 1), (1, 1) and legend at (1, 0) I am trying to do that by draw a pie chart in (0,0) (0, 1), and a pie chart that span 2 column at second row. I can left-align the legend. However, I don't know how to right align the pie chart.
labels = ["Very negative", "Negative", "Neutral", "Positive", "Very positive"]
dev_sentences = [139, 289, 229, 279, 165]
test_sentences = [279, 633, 389, 510, 399]
train_sentences = [1092, 2218, 1624, 2322, 1288]
plt.clf()
plt.cla()
plt.close()
gs = gridspec.GridSpec(2, 2)
ax1= plt.subplot(gs[0, 0])
ax1.pie(dev_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal')
ax2= plt.subplot(gs[0, 1])
ax2.pie(test_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax2.axis('equal')
ax3 = plt.subplot(gs[1, :])
ax3.pie(train_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax3.axis('equal')
ax3.legend(labels=labels, loc="upper left")
I want somehow move the third pie chart (ax3) toward right a bit.
答案 0 :(得分:3)
您可以通过在位置(1,1)中绘制第三个子图,然后将图例移到此子图之外,使其实际上占据位置(1,0)来实现此目的。这可以使用bbox_to_anchor
完成。可以找到文档here。
labels = ["Very negative", "Negative", "Neutral", "Positive", "Very positive"]
dev_sentences = [139, 289, 229, 279, 165]
test_sentences = [279, 633, 389, 510, 399]
train_sentences = [1092, 2218, 1624, 2322, 1288]
plt.clf()
plt.cla()
plt.close()
gs = gridspec.GridSpec(2, 2)
ax1= plt.subplot(gs[0, 0])
ax1.pie(dev_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal')
ax2= plt.subplot(gs[0, 1])
ax2.pie(test_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax2.axis('equal')
ax3 = plt.subplot(gs[1, 1])
ax3.pie(train_sentences, autopct='%1.1f%%',
shadow=True, startangle=90)
ax3.axis('equal')
# use bbox_to_anchor to move your legend to wherever you like
ax3.legend(labels=labels, bbox_to_anchor=(-1,1), loc="upper left")
plt.show()
产生以下图表: