Skip to main content
 首页 » 编程设计

python之多个图例到 matplotlib 饼图

2024年10月17日9zhujiabin

我正在用 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()