如何在 Python 中为图表添加图例?
简介…
图表的核心目的是使数据易于理解。“一张图片胜过千言万语”意味着无法用语言表达的复杂思想可以通过单个图像/图表来传达。
在绘制包含大量信息的图表时,图例可能有助于显示相关信息,从而提高对所呈现数据的理解。
如何操作…
在 matplotlib 中,图例可以通过多种方式呈现。注释用于引起读者对特定点的注意,也有助于读者理解图表上显示的信息。
1. 通过打开 Python 命令提示符并执行 pip install matplotlib 来安装 matplotlib。
2. 准备要显示的数据。
示例
import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),)
3. 将数据拆分为每个公司手机单元的数组。
示例
# data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold] # data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold] # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2
4. 使用准备好的数据创建条形图。每个产品的销量都会调用 .bar,指定其位置和销量。
使用 xy 和 xytext 属性添加注释。查看数据,Google Pixel 手机销量下降了 50%,即从 2019 年的 1000 万台下降到 2022 年的 500 万台。因此,我们将设置文本和注释到我们的最后一个条形。
最后,我们将使用 legend 参数添加图例。默认情况下,matplotlib 会在数据重叠最少的地方绘制图例。
示例
plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow') # Set X-axis as years plt.xticks(Position, Years) # Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions') # Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05)) # Set the legent plt.legend(mobile, title='Manufacturers')
输出
<matplotlib.legend.Legend at 0x19826618400>
如果您觉得在图表内添加图例会显得杂乱,可以使用 bbox_to_anchor 选项将图例绘制到外部。bbox_to_anchor 具有 (X, Y) 位置,其中 0 是图表的左下角,1 是右上角。
**注意:** - 使用 .subplots_adjust 调整图例的起始和结束位置。
例如,right=0.50 值表示它在绘图右侧保留 50% 的屏幕空间。left 的默认值为 0.125,表示它在左侧保留 12.5% 的空间。
输出
plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1, 0.8)) plt.subplots_adjust(right=1.2)
示例
6. 最后,让我们保存图形。
import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),) # data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold] # data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold] # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2 plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow') # Set X-axis as years plt.xticks(Position, Years) # Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions') # Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05)) # Set the legent plt.legend(mobile, title='Manufacturers') plt.legend(mobile, title='Manufacturers') plt.subplots_adjust(right=1.2) # plt.show() plt.savefig('MobileSales.png')
广告