简体   繁体   中英

Align pie chart left or right in multicolumn span subplot in girdspec

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.

You can achieve this by plotting your third subplot in the position (1,1) and then move the legend outside of this subplot so that it, in effect, occupies the position (1,0). This can be done using bbox_to_anchor . The documentation can be found 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()

Which produces the following graph:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM