python - matplotlib 饼图的多个图例?

标签 python matplotlib charts legend

我正在使用 Python 进行编码并测试 Matplotlib。我正在尝试添加多个图例,因为我有 2 个饼图。使用这个http://matplotlib.org/users/legend_guide.html我有 2 个多个图例,但颜色相同。对于每个饼图,我有 2 种不同的颜色,因此我希望它们各自的图例具有相同的颜色。

另外,是否可以将图例放在更靠近窗口边框的位置?因为图例是一个很长的短语,我不希望第二个图例出现在屏幕中间。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

#def pieChart()
# Data to plot
labels = 'Participaram', 'Não participaram'
sizes = [215, 130]
colors = ['gold', 'yellowgreen']
explode = (0.1, 0)  # explode 1st slice

labels2 = 'Só visualizam dúvidas alheias', 'Mandaram e visualizam'
sizes2 = [215, 130]
colors2 = ['lightskyblue', 'lightcoral']
explode2 = (0, 0.08)  # explode 1st slice

# Plot
plt.pie(sizes, explode=explode,  colors=colors2,autopct='%1.1f%%', shadow=True, startangle=90, center = (-2,0))

plt.pie(sizes2, explode=explode2,  colors=colors,autopct='%1.1f%%', shadow=True, startangle=45, center = (2,0))

first_legend = plt.legend(labels,loc = 2)
ax = plt.gca().add_artist(first_legend)
second_legend = plt.legend(labels2,loc = 4,ncol=1)

plt.axis('equal')
plt.show()

enter image description here

最佳答案

在图中定义两个轴来分别绘制每个饼图并自动调整使用tight_layout:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

#def pieChart()
# Data to plot
labels = u'Participaram', u'Não participaram'
sizes = [215, 130]
colors = ['gold', 'yellowgreen']
explode = (0.1, 0)  # explode 1st slice

labels2 = [u'Só visualizam dúvidas alheias', u'Mandaram e visualizam']
sizes2 = [215, 130]
colors2 = ['lightskyblue', 'lightcoral']
explode2 = (0, 0.08)  # explode 1st slice

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# Plot
ax1.pie(sizes, explode=explode,  colors=colors2, autopct='%1.1f%%', 
        shadow=True, startangle=90, center = (-2,0))

ax2.pie(sizes2, explode=explode2,  colors=colors,autopct='%1.1f%%', 
        shadow=True, startangle=45, center = (2,0))

first_legend = ax1.legend(labels, loc = 2)
second_legend = ax2.legend(labels2, loc = 2)

ax1.axis('equal')
ax2.axis('equal')
plt.tight_layout()
plt.show()

关于python - matplotlib 饼图的多个图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40670896/

相关文章:

python - 如何让 Django UpdateView 仅在第一次工作?

python - 如何在刻度(matplotlib)之间对齐条形图中的条形图?

javascript - C3条形图-自定义X轴标签

iphone - CorePlot : how to set touch event, 当用户单击图表上的 CandleStick 时,它可以显示蜡烛 X 和 Y 值吗?

javascript - charts.js饼图中的千位分隔符

python - 在 Pandas 中结合 CustomBusinessDay 和 BusinessHour 类

python - 为什么 numpy 和 random 模块为同一种子提供不同的随机数?

python - 我无法专注于上传按钮来上传简历

python - 用新图形更新 wxpython 图形 Canvas

python - 如何在 matplotlib 中绘制滞后现象?