简体   繁体   English

在girdspec中的多列范围子图中左右对齐饼图

[英]Align pie chart left or right in multicolumn span subplot in girdspec

I have 2x2 gird. 我有2x2网格。 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. 我想要位置(0,0)(0,1),(1,1)的饼图和(1,0)的图例我试图通过在(0,0)中绘制饼图来做到这一点(0, 1),以及在第二行跨越2列的饼图。 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. 我想以某种方式将第三个饼图(ax3)向右移动一点。

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). 您可以通过在位置(1,1)中绘制第三个子图,然后将图例移到此子图之外,使其实际上占据位置(1,0)来实现此目的。 This can be done using bbox_to_anchor . 这可以使用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: 其中生成以下图表:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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