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平臺上瀏覽其他的數據集,并進行可視化!