您的位置:首頁>正文

超實用!用Python進行資料視覺化的9種常見方法!

如同藝術家們用繪畫讓人們更貼切的感知世界, 資料視覺化也能讓人們更直觀的傳遞資料所要表達的資訊。

我們今天就分享一下如何用 Python 簡單便捷的完成資料視覺化。

其實利用 Python 視覺化資料並不是很麻煩, 因為 Python 中有兩個專用於視覺化的庫 matplotlib 和 seaborn 能讓我們很容易的完成任務。

Matplotlib:基於Python的繪圖庫, 提供完全的 2D 支援和部分 3D 圖像支援。 在跨平臺和互動式環境中生成高品質資料時, matplotlib 會很有幫助。 也可以用作製作動畫。 Seaborn:該 Python 庫能夠創建富含信息量和美觀的統計圖形。 Seaborn 基於 matplotlib, 具有多種特性, 比如內置主題、調色板、可以視覺化單變數資料、雙變數資料, 線性回歸資料和資料矩陣以及統計型時序資料等, 能讓我們創建複雜的視覺化圖形。

我們用 Python 可以做出哪些視覺化圖形?

那麼這裡可能有人就要問了, 我們為什麼要做資料視覺化?比如有下面這個圖表:

當然如果你把這張圖表丟給別人, 他們倒是也能看懂, 但無法很直觀的理解其中的資訊, 而且這種形式的圖表看上去也比較 low, 這個時候我們如果換成直觀又美觀的視覺化圖形, 不僅能突顯逼格, 也能讓人更容易的看懂資料。

下面我們就用上面這個簡單的資料集作為例子,

展示用 Python 做出9種視覺化效果, 並附有相關代碼。

導入資料集

import matplotlib.pyplot as pltimport pandas as pddf=pd.read_excel("E:/First.xlsx", "Sheet1")

視覺化為長條圖

fig=plt.figure #Plots in matplotlib reside within a figure object, use plt.figure to create new figure#Create one or more subplots using add_subplot, because you can't create blank figureax = fig.add_subplot(1,1,1)#Variableax.hist(df['Age'],bins = 7) # Here you can play with number of binsLabels and Titplt.title('Age distribution')plt.xlabel('Age')plt.ylabel('#Employee')plt.show

視覺化為箱線圖

import matplotlib.pyplot as pltimport pandas as pdfig=plt.figureax = fig.add_subplot(1,1,1)#Variableax.boxplot(df['Age'])plt.show

視覺化為小提琴圖

import seaborn as sns sns.violinplot(df['Age'], df['Gender']) #Variable Plotsns.despine

視覺化為橫條圖

var = df.groupby('Gender').Sales.sum #grouped sum of sales at Gender levelfig = plt.figureax1 = fig.add_subplot(1,1,1)ax1.set_xlabel('Gender')ax1.set_ylabel('Sum of Sales')ax1.set_title("Gender wise Sum of Sales")var.plot(kind='bar')

視覺化為折線圖

var = df.groupby('BMI').Sales.sumfig = plt.figureax1 = fig.add_subplot(1,1,1)ax1.set_xlabel('BMI')ax1.set_ylabel('Sum of Sales')ax1.set_title("BMI wise Sum of Sales")var.plot(kind='line')

視覺化為堆疊柱狀圖

var = df.groupby(['BMI','Gender']).Sales.sumvar.unstack.plot(kind='bar',stacked=True, color=['red','blue'], grid=False)

視覺化為散點圖

fig = plt.figureax = fig.add_subplot(1,1,1)ax.scatter(df['Age'],df['Sales']) #You can also add more variables here to represent color and size.plt.show

視覺化為泡泡圖

fig = plt.figureax = fig.add_subplot(1,1,1)ax.scatter(df['Age'],df['Sales'], s=df['Income']) # Added third variable income as size of the bubbleplt.show

視覺化為餅狀圖

var=df.groupby(['Gender']).sum.stacktemp=var.unstacktype(temp)x_list = temp['Sales']label_list = temp.indexpyplot.axis("equal") #The pie chart is oval by default. To make it a circle use pyplot.axis("equal")#To show the percentage of each pie slice, pass an output format to the autopctparameter plt.pie(x_list,labels=label_list,autopct="%1.1f%%") plt.title("Pastafarianism expenses")plt.show

視覺化為熱度圖

import numpy as np#Generate a random number, you can refer your data values alsodata = np.random.rand(4,2)rows = list('1234') #rows categoriescolumns = list('MF') #column categoriesfig,ax=plt.subplots#Advance color controlsax.pcolor(data,cmap=plt.cm.Reds,edgecolors='k')ax.set_xticks(np.arange(0,2)+0.5)ax.set_yticks(np.arange(0,4)+0.5)# Here we position the tick labels for x and y axisax.xaxis.tick_bottomax.yaxis.tick_left#Values against each labelsax.set_xticklabels(columns,minor=False,fontsize=20)ax.set_yticklabels(rows,minor=False,fontsize=20)plt.show

你也可以自己試著根據兩個變數比如性別(X 軸)和 BMI(Y 軸)繪出熱度圖。

結語

本文我們分享了如何利用 Python 及 matplotlib 和 seaborn 庫製作出多種多樣的視覺化圖形。通過上面的例子,我們應該可以感受到利用視覺化能多麼美麗的展示資料。而且和其它語言相比,使用 Python 進行視覺化更容易簡便一些。

參考資料:

https://www. analyticsvidhya.com/blo g/2015/05/data-visualization-python/

視覺化為堆疊柱狀圖

var = df.groupby(['BMI','Gender']).Sales.sumvar.unstack.plot(kind='bar',stacked=True, color=['red','blue'], grid=False)

視覺化為散點圖

fig = plt.figureax = fig.add_subplot(1,1,1)ax.scatter(df['Age'],df['Sales']) #You can also add more variables here to represent color and size.plt.show

視覺化為泡泡圖

fig = plt.figureax = fig.add_subplot(1,1,1)ax.scatter(df['Age'],df['Sales'], s=df['Income']) # Added third variable income as size of the bubbleplt.show

視覺化為餅狀圖

var=df.groupby(['Gender']).sum.stacktemp=var.unstacktype(temp)x_list = temp['Sales']label_list = temp.indexpyplot.axis("equal") #The pie chart is oval by default. To make it a circle use pyplot.axis("equal")#To show the percentage of each pie slice, pass an output format to the autopctparameter plt.pie(x_list,labels=label_list,autopct="%1.1f%%") plt.title("Pastafarianism expenses")plt.show

視覺化為熱度圖

import numpy as np#Generate a random number, you can refer your data values alsodata = np.random.rand(4,2)rows = list('1234') #rows categoriescolumns = list('MF') #column categoriesfig,ax=plt.subplots#Advance color controlsax.pcolor(data,cmap=plt.cm.Reds,edgecolors='k')ax.set_xticks(np.arange(0,2)+0.5)ax.set_yticks(np.arange(0,4)+0.5)# Here we position the tick labels for x and y axisax.xaxis.tick_bottomax.yaxis.tick_left#Values against each labelsax.set_xticklabels(columns,minor=False,fontsize=20)ax.set_yticklabels(rows,minor=False,fontsize=20)plt.show

你也可以自己試著根據兩個變數比如性別(X 軸)和 BMI(Y 軸)繪出熱度圖。

結語

本文我們分享了如何利用 Python 及 matplotlib 和 seaborn 庫製作出多種多樣的視覺化圖形。通過上面的例子,我們應該可以感受到利用視覺化能多麼美麗的展示資料。而且和其它語言相比,使用 Python 進行視覺化更容易簡便一些。

參考資料:

https://www. analyticsvidhya.com/blo g/2015/05/data-visualization-python/

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示