我正在使用 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()
最佳答案
在图中定义两个轴来分别绘制每个饼图并自动调整使用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/