python matplotlib数据可视化教程_matplotlib的Python数据可视化和探索——入门指南

matplotlib——最受欢迎的Python库,用于数据可视化和探索

我喜欢在Python中使用matplotlib。这是我学会掌握的第一个可视化库,此后一直存在。matplotlib是最受欢迎的用于数据可视化和探索的Python库,这是有原因的——它提供的灵活性和敏捷性是无与伦比的!

Matplotlib提供了一种简单而全面的可视化方法来介绍我们的发现。我们将在本教程中很快看到,有很多可视化可供选择,以展示我们的结果。

从直方图到散点图,matplotlib设置了一系列颜色,主题,调色板和其他选项以自定义和个性化我们的图。无论您是在为机器学习项目执行数据探索,还是只是想创建令人眼花and乱的图表,matplotlib都非常有用。

什么是matplotlib?

在深入探讨本文的关键之前,让我们对matplotlib进行正式定义。如果这是您第一次听说matplotlib,那么这里是官方描述:

“ Matplotlib是一个Python 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版物质量的图形。Matplotlib可用于Python脚本,Python和IPython外壳,Jupyter笔记本,Web应用程序服务器以及四个图形用户界面工具包。”

您可以使用matplotlib绘制各种图表和可视化效果。在本教程中,我将探索matplotlib Python库中最常见的图。我们将首先了解手头的数据集,然后开始使用matplotlib构建不同的图,包括散点图和折线图!

这是我们将使用matplotlib设计的可视化

条状图饼形图箱形图直方图折线图和子图散点图了解数据集和问题陈述

在介绍不同的可视化和图表类型之前,我想花一些时间来理解数据。这是机器学习流程中的关键部分,我们应该充分注意它。

我们将在此matplotlib教程中分析“ 食品需求预测”项目。该项目的目的是预测客户在接下来的几周内将向公司下达的食品订单数量。当然,我们只会在项目的探索阶段花费时间。

让我们首先导入相关的库:

import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn')

我使用了matplotlib样式表来使我们的绘图看起来整洁漂亮。在这里,我使用了“ seaborn”样式表。但是,Matplotlib中还有很多其他样式表,您可以使用它们来最适合您的表示样式。

我们的数据集包含三个数据框:df_meal描述餐点,df_center描述食物中心,df_food描述整体食物顺序。在下面看看它们:

df_meal = pd.read_csv('C:\\Users\Dell\\Desktop\\train_food\\meal_info.csv')

df_meal.head()

df_center = pd.read_csv('C:\\Users\Dell\\Desktop\\train_food\\fulfilment_center_info.csv')

df_center.head()

我将首先将所有三个数据框合并为一个数据框。这将使在绘制数据时更容易处理数据:

df_food = pd.read_csv('C:\\Users\Dell\\Desktop\\train_food\\train_food.csv')

df_food.head()

正确–现在,让我们进入可以在Python中使用matplotlib创建的不同图表类型!

使用matplotlib的条形图

首先,我们要查找客户从公司购买的最受欢迎的食品。

我将使用熊猫Pivot_table函数来查找食品的每个类别的订单总数:

table = pd.pivot_table(data=df,index='category',values='num_orders',aggfunc=np.sum)table

接下来,我将尝试使用条形图对此进行可视化。

当我们需要比较同一类别中类别值的数量时,最好使用条形图。

条形图是使用matplotlib中的plt.bar()生成的:

#bar graphplt.bar(table.index,table['num_orders']) #xticks plt.xticks(rotation=70) #x-axis labels plt.xlabel('Food item') #y-axis labels plt.ylabel('Quantity sold') #plot title plt.title('Most popular food') #save plot plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_6.png',dpi=300,bbox_inches='tight') #display plot plt.show();

标记轴始终很重要。您可以通过使用plt.xlabel()和plt.ylabel()函数来完成此操作。您可以使用plt.title()来命名绘图的标题。如果您的xtick重叠,请使用plt.xticks()中的rotation参数旋转它们,以便观众轻松查看。

您可以使用plt.savefig()函数通过将文件路径作为参数来保存图形。最后,请始终使用plt.show()显示图。

在分析情节时,我们可以看到饮料是该公司出售的最受欢迎的食品。等等,是因为几乎所有的饭菜都卖光了吗?是最流行的食物?

让我们将食物总订单除以其中所含独特餐点的数量。

#dictionary for meals per food itemitem_count = {} for i in range(table.index.nunique()): item_count[table.index[i]] = table.num_orders[i]/df_meal[df_meal['category']==table.index[i]].shape[0] #bar plot plt.bar([x for x in item_count.keys()],[x for x in item_count.values()],color='orange') #adjust xticksplt.xticks(rotation=70) #label x-axisplt.xlabel('Food item') #label y-axisplt.ylabel('No. of meals') #label the plotplt.title('Meals per food item') #save plotplt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_7.png',dpi=300,bbox_inches='tight') #display plotplt.show();

是的,我们的假设是正确的!饭碗确实是该公司出售的最受欢迎的食品。

条形图不应用于连续值。

使用matplotlib的饼图

现在让我们查看每种美食的订单比例。

饼图适合于显示同一类别中项目的比例分布。

#dictionary for cuisine and its total ordersd_cuisine = {} #total number of ordertotal = df['num_orders'].sum() #find ratio of orders per cuisinefor i in range(df['cuisine'].nunique()): #cuisinec = df['cuisine'].unique()[i] #num of orders for the cuisinec_order = df[df['cuisine']==c]['num_orders'].sum()d_cuisine[c] = c_order/total

让我们绘制饼图:

#pie plot plt.pie([x*100 for x in d_cuisine.values()],labels=[x for x in d_cuisine.keys()],autopct='%0.1f',explode=[0,0,0.1,0]) #label the plot plt.title('Cuisine share %') plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_8.png',dpi=300,bbox_inches='tight') plt.show();

我使用plt.pie()绘制饼图并调整其参数以使其更具吸引力所述autopct参数被用于馅饼内打印值图表高达1个小数位该爆炸参数是用来抵消意大利楔,使其从脱颖而出。这样一来,观众就可以立即清楚地看到人们喜欢意大利美食!当类别中有很多项目时,饼图将变得无用。这将减小每个切片的大小,并且项目之间没有区别。

使用matplotlib的箱线图

由于我们正在讨论美食,因此让我们看看哪一种是最昂贵的美食!为此,我将使用Box Plot。

箱形图提供了有关分为不同组的数字数据分布的统计信息。这对于检测每个组中的离群值很有用。

箱的下部,中部和上部表示第25,第50,和第75个百分位值分别为

最高晶须代表Q3 + 1.5 * IQR底部晶须代表Q1-1.5 * IQR离群值显示为散点显示数据偏斜#dictionary for base price per cuisinec_price = {}for i in df['cuisine'].unique(): c_price[i] = df[df['cuisine']==i].base_price

绘制下面的箱线图:

#plotting boxplot plt.boxplot([x for x in c_price.values()],labels=[x for x in c_price.keys()]) #x and y-axis labels plt.xlabel('Cuisine') plt.ylabel('Price') #plot title plt.title('Analysing cuisine price') #save and display plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_9.png',dpi=300,bbox_inches='tight') plt.show();

欧陆式美食是该公司提供的最昂贵的美食!即使是中间价格也高于所有美食的最高价格。

箱形图未显示每个组内数据点的分布。

使用matplotlib的直方图

在价格这个话题上,我们是否忘了检查基本价格和结帐价格?不用担心,我们将使用直方图来做到这一点。

直方图通过将数据分段到不同的bin中来显示数字数据在连续间隔中的分布。对于检查数据中的偏斜度很有用。

由于base_price是连续变量,因此我们将使用直方图以不同的不同顺序检查其范围。我们可以使用plt.hist()做到这一点。

但是令人困惑的是,箱的数量应该是多少?默认情况下,它是10。但是,没有正确的答案,您可以根据数据集对其进行更改以使其可视化。

#plotting histogram plt.hist(df['base_price'],rwidth=0.9,alpha=0.3,color='blue',bins=15,edgecolor='red') #x and y-axis labels plt.xlabel('Base price range') plt.ylabel('Distinct order') #plot title plt.title('Inspecting price effect') #save and display the plot plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_10.png',dpi=300,bbox_inches='tight') plt.show();

我选择的箱数为15,很明显,大多数订单的底价约为300。

容易将直方图与条形图混淆。但是请记住,直方图用于连续数据,而条形图用于分类数据。

使用matplotlib绘制线图和子图

折线图对于可视化连续时间间隔内的数值趋势很有用。

公司的每周和每月销售额如何变化?这是决定或破坏营销策略的关键业务问题。

在探索之前,我将创建两个列表来存储公司的按周和按月收入:

#new revenue column df['revenue'] = df.apply(lambda x: x.checkout_price*x.num_orders,axis=1) #new month column df['month'] = df['week'].apply(lambda x: x//4) #list to store month-wise revenue month=[] month_order=[] for i in range(max(df['month'])): month.append(i) month_order.append(df[df['month']==i].revenue.sum()) #list to store week-wise revenue week=[] week_order=[] for i in range(max(df['week'])): week.append(i) week_order.append(df[df['week']==i].revenue.sum())

我将使用两个并排绘制的线图来比较公司每周和每月的收入。为此,我将使用plt.subplots()函数。

Matplotlib子图使您可以轻松查看和比较同一图中的不同图。

为了理解这个功能是如何工作的,你需要知道什么图,轴,和轴处于matplotlib阴谋。

图是Matplotlib图的最外层容器。可以有单个或多个小区,称为斧,一个内图。这些轴均包含x和y轴,称为Axis。

所述plt.subplots()图返回图和轴。您可以提供如何在图形中显示轴作为功能的输入。这些将使用nrows和ncols参数进行调整。您甚至可以使用figsize参数来调整图形的大小。

轴以列表形式返回。要绘制特定轴,可以将它们作为列表对象进行访问。其余绘图与简单绘图相同:

#subplots returns a Figure and an Axes object fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(20,5)) #manipulating the first Axes ax[0].plot(week,week_order) ax[0].set_xlabel('Week') ax[0].set_ylabel('Revenue') ax[0].set_title('Weekly income') #manipulating the second Axes ax[1].plot(month,month_order) ax[1].set_xlabel('Month') ax[1].set_ylabel('Revenue') ax[1].set_title('Monthly income') #save and display the plot plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_11.png',dpi=300,bbox_inches='tight') plt.show();

我们可以看到,随着周数和月数的增加,食品订单数量呈上升趋势,尽管这种趋势不是很明显。

6.使用matplotlib进行散点图

最后,我将尝试分析中心类型是否对来自不同中心类型的订单数量有任何影响。我将通过比较同一图中的散点图,箱形图和条形图来做到这一点。

我们已经看到了箱线图和条形图的使用,但是散点图有其自身的优势。

散点图对于显示两个变量之间的关系很有用。使用散点图可以轻松发现数据中变量或离群值之间的任何相关性。

center_type_name = ['TYPE_A','TYPE_B','TYPE_C'] #relation between op area and number of orders op_table=pd.pivot_table(df,index='op_area',values='num_orders',aggfunc=np.sum) #relation between center type and op area c_type = {} for i in center_type_name: c_type[i] = df[df['center_type']==i].op_area #relation between center type and num of orders center_table=pd.pivot_table(df,index='center_type',values='num_orders',aggfunc=np.sum) #subplots fig,ax = plt.subplots(nrows=3,ncols=1,figsize=(8,12)) #scatter plots ax[0].scatter(op_table.index,op_table['num_orders'],color='pink') ax[0].set_xlabel('Operation area') ax[0].set_ylabel('Number of orders') ax[0].set_title('Does operation area affect num of orders?') ax[0].annotate('optimum operation area of 4 km^2',xy=(4.2,1.1*10**7),xytext=(7,1.1*10**7),arrowprops=dict(facecolor='black', shrink=0.05),fontsize=12) #boxplot ax[1].boxplot([x for x in c_type.values()], labels=[x for x in c_type.keys()]) ax[1].set_xlabel('Center type') ax[1].set_ylabel('Operation area') ax[1].set_title('Which center type had the optimum operation area?') #bar graph ax[2].bar(center_table.index,center_table['num_orders'],alpha=0.7,color='orange',width=0.5) ax[2].set_xlabel('Center type') ax[2].set_ylabel('Number of orders') ax[2].set_title('Orders per center type') #show figure plt.tight_layout() plt.savefig('C:\\Users\\Dell\\Desktop\\AV Plotting images\\matplotlib_plotting_12.png',dpi=300,bbox_inches='tight') plt.show();

通过散点图可以立即看到中心的最佳操作区域为4 km sq。箱线图显示TYPE_A中心类型的最佳大小中心数量最多,这是因为紧凑的盒子的中位数约为4 km sq。其中,客户下的订单比其他任何类型的中心都要多。

尾注

现在离在Matplotlib中创建精美的绘图又近了一步。但是,掌握绘图的最佳方法是练习练习再练习!

为此,我建议您在DataHack平台上浏览其他的数据集,并进行可视化!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值