Python進行數據可視化的9種常見方法,易懂實用!

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

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

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

那麼這裏可能有人就要問了,我們爲什麼要做數據可視化?比如有下面這個圖表:

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

下面我們就用上面這個簡單的數據集作爲例子,展示用 Python 做出9種可視化效果,並附有相關代碼。

導入數據集

import matplotlib.pyplot as plt
import pandas as pd
df=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 figure
ax = fig.add_subplot(1,1,1)
#Variable
ax.hist(df['Age'],bins = 7) # Here you can play with number of bins
Labels and Tit
plt.title('Age distribution')
plt.xlabel('Age')
plt.ylabel('#Employee')
plt.show()

可視化爲箱線圖

import matplotlib.pyplot as plt
import pandas as pd
fig=plt.figure()
ax = fig.add_subplot(1,1,1)
#Variable
ax.boxplot(df['Age'])
plt.show()

可視化爲小提琴圖

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

可視化爲條形圖

var = df.groupby('Gender').Sales.sum() #grouped sum of sales at Gender level
fig = plt.figure()
ax1 = 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.sum()
fig = plt.figure()
ax1 = 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.sum()
var.unstack().plot(kind='bar',stacked=True,  color=['red','blue'], grid=False)

<figure style="margin: 1em 0px; color: rgb(26, 26, 26); font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", "Source Han Sans SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

image

</figure>

可視化爲散點圖

fig = plt.figure()
ax = 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.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(df['Age'],df['Sales'], s=df['Income']) # Added third variable income as size of the bubble
plt.show()

可視化爲餅狀圖

var=df.groupby(['Gender']).sum().stack()
temp=var.unstack()
type(temp)
x_list = temp['Sales']
label_list = temp.index
pyplot.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()

<figure style="margin: 1em 0px; color: rgb(26, 26, 26); font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", "Source Han Sans SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

image

</figure>

可視化爲熱度圖

import numpy as np
#Generate a random number, you can refer your data values also
data = np.random.rand(4,2)
rows = list('1234') #rows categories
columns = list('MF') #column categories
fig,ax=plt.subplots()
#Advance color controls
ax.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 axis
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
#Values against each labels
ax.set_xticklabels(columns,minor=False,fontsize=20)
ax.set_yticklabels(rows,minor=False,fontsize=20)
plt.show()

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

結語

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章