如何在Matplot库中创建自定义图例?

时间:2019-08-13 00:32:35

标签: matplotlib plot seaborn legend

我创建了一个图形,该图形将三个变量拉入堆叠的条形图中,但无法显示图例来显示说明。

我试图将别名r更改为使用我想要的名称(运营商延迟,天气延迟和飞机延迟起飞),但这没有用。

# Create percents
r = [0,1,2,3,4]
totals = [i+j+k for i,j,k in zip(df_delay_type['CarrierDelay'], df_delay_type['WeatherDelay'], df_delay_type['LateAircraftDelay'])]
CarrierDelay = [i / j * 100 for i,j in zip(df_delay_type['CarrierDelay'], totals)]
WeatherDelay = [i / j * 100 for i,j in zip(df_delay_type['WeatherDelay'], totals)]
LateAircraftDelay = [i / j * 100 for i,j in zip(df_delay_type['LateAircraftDelay'], totals)]

# plot
barWidth = 0.85

names = ('American Airlines Inc.','Alaska Airlines Inc.','Delta Air Lines Inc.','United Air Lines Inc.','Southwest Airlines Co.')
# Create green Bars
plt.bar(r, CarrierDelay, color='#b5ffb9', edgecolor='white', width=barWidth)
# Create orange Bars
plt.bar(r, WeatherDelay, bottom=CarrierDelay, color='#f9bc86', edgecolor='white', width=barWidth)
# Create blue Bars
plt.bar(r, LateAircraftDelay, bottom=[i+j for i,j in zip(CarrierDelay, WeatherDelay)], color='#a3acff', edgecolor='white', width=barWidth)

# Custom x axis
plt.xticks(r, names, rotation = 0, fontsize=12, fontweight='bold')
plt.xlabel("Airlines", fontsize=11, fontweight='bold')
plt.ylabel('Percent of Delay', fontsize=11, fontweight='bold')
plt.title ('Delays by Type and Carrier',  fontsize=14, fontweight='bold') 

# Show graphic
plt.legend(r)
plt.show()

此代码生成的图例在颜色旁边显示“ 0”,“ 1”和“ 2”,但我想改为看到“ Carrier Delay”,“ Weather Delay”和“ Late Aircraft Delay”。

0 个答案:

没有答案