【问题标题】:Align pie chart left or right in multicolumn span subplot in girdspec在gridspec的多列跨度子图中左对齐或右对齐饼图
【发布时间】:2017-12-14 10:08:09
【问题描述】:

我有 2x2 网格。我想要位置 (0,0) (0, 1), (1, 1) 的饼图和 (1, 0) 的图例 我试图通过在 (0,0) (0, 1) 中绘制一个饼图和一个在第二行跨越 2 列的饼图来做到这一点。我可以左对齐图例。但是,我不知道如何正确对齐饼图。

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")

我想以某种方式将第三个饼图 (ax3) 向右移动一点。

【问题讨论】:

  • 您是说“我想要位置 (0,0) (0, 1), (1, 1) 的饼图”;但是,您不要将第三个条形图放在位置 (1,1)。有什么理由吗?我还建议阅读Legend overlaps with the pie chart
  • 嗨@ImportanceOfBeingErnest,我想要左边的图例。因此,我认为让饼图跨越 2 列,然后对齐左侧的图例和右侧的饼图可能会起作用。顺便说一句,DavidG 回答对我有用。
  • 我明白了,在轴内对齐饼图实际上是可能的,但我不建议这样做,因为它比将图表放置在位置 (1,1) 和图例要多得多在位置 (1,0),就像在下面的答案中一样。

标签: python matplotlib charts alignment


【解决方案1】:

您可以通过在位置 (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()

这会产生以下图表:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2018-01-24
    • 2012-10-13
    • 2022-07-15
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多