做資料分析的時候,自己繪制圖像的時候總是遇到各種想不起來的代碼,總是需要去查,我覺得自己總結一下python的繪圖手法,對後面自己能力的建構會很有幫助。
本片總結涉及到的matplotlib繪圖的基礎内容包括:走勢圖(也稱折線圖),直方圖,餅圖,散點圖,柱狀圖,條形圖,堆疊圖,以及圖示、圖例、子圖和儲存圖像的使用方法
繪圖之前需要建構一些資料,下面随機建構一群學生的身高、體重、年齡、國文成績的資料
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import
np.random.seed(20211028)
height = np.random.randint(150,200,100)
weight = np.random.randint(40,100,100)
old = np.random.randint(1,100,100)
grade = np.random.randint(0,100,100)
先來繪制最簡單的走勢圖
plt.plot(height)
plt.show()

繪圖之後我想給圖像添加x軸和y軸的說明
plt.plot(height)
plt.xlabel('students')
plt.ylabel('height')
plt.show()
我能不能在一張圖像中畫兩條走勢圖呢
plt.plot(height)
plt.plot(weight)
plt.xlabel('students')
plt.ylabel('height or weight')
plt.show()
還真可以哦,但是我能不能畫三條呢,再試試
plt.plot(height)
plt.plot(weight)
plt.plot(old)
plt.xlabel('students')
plt.ylabel('height or weight or old')
plt.show()
也是可以的,應該在一張圖像中可以繪制很多很多條走勢圖才對。
如果單獨看這個圖像,沒有圖像标注的話,我們也不知道哪個顔色的線條對應哪個資料呀,是以我們需要給圖像添加圖示
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.legend() # 将圖示展示出來
plt.show() # 将圖像展示出來
然後一般來說,我們還需要給圖像設定一個标題,
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.title('plot of students height')
plt.legend()
plt.show()
如果有需要,我們還需要将圖像儲存起來
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.title('plot of students height')
plt.savefig('./plot_of_students_height.png')
plt.legend()
plt.show()
先我們畫的圖像,都是預設的畫布大小,我們沒有指定所需要的畫布大小,那麼畫布大小該如何指定呢
plt.figure(figsize=(12,6)) # 指定畫布大小(長、寬)
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.title('plot of students height')
plt.legend()
plt.show()
畫布變大之後,感覺圖像變模糊好多,那我們怎麼讓圖像分辨率變高一點呢,可以指定dpi這個變量
plt.figure(figsize=(12,6),dpi=100) # 指定畫布大小(長、寬),指定分辨率為100,變清晰好多
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.title('plot of students height')
plt.legend()
plt.show()
為了資料更加明顯,我們還可以給圖像添加網格線,這樣子,對于資料落在那個範圍就心中有數啦
plt.figure(figsize=(12,6),dpi=100) # 指定畫布大小(長、寬),指定分辨率為100,變清晰好多
plt.plot(height,label='height')
plt.plot(weight,label='weight')
plt.xlabel('students')
plt.ylabel('height or weight')
plt.title('plot of students height')
plt.grid() # 生成網格
plt.legend()
plt.show()
總結一下,我們使用plt畫圖一般需要的步驟,完整代碼
plt.figure(figsize=(12,6),dpi=100) # 1、指定畫布大小
plt.plot(height,label='height') # 畫圖,如果你想話直方圖就換乘直方圖,自由性在這裡
plt.plot(weight,label='weight') # 畫圖,如果你想話直方圖就換乘直方圖,自由性在這裡
plt.xlabel('students') # 指定x軸說明
plt.ylabel('height or weight') # 指定y軸說明
plt.title('plot of students height') # 指定圖像名字
plt.grid() # 生成網格
plt.savefig('./plot_of_students_height.png') # 根據自己需求是否儲存圖像
plt.legend() # 顯示圖例,圖例包括圖示等
plt.show() # 展示圖檔
現在來試一下如何繪制分布直方圖,這個也是用得最多的一類了吧
plt.hist(height) # 繪圖
plt.show() # 展示
不難看出,模型畫出來的直方柱子隻有10條,為了看清分布的細節,我們嘗試調節一下直方柱子的數量
plt.hist(height,bins=30)
plt.show()
直方圖的橫軸表示身高值,豎軸表示該身高值的頻數。我們能不能将頻數變成頻率呢,答案是可以的
plt.hist(height,bins=30,density=True)
plt.show()
假設現在我隻想研究身高在180到200範圍内資料的分布情況,我們能不能限制範圍來繪制直方圖呢,答案也是可以的
plt.hist(height,bins=30,density=True,range=(180,200))
plt.show()
可以看到,192.5身高的人數量是最多的。但是這些資料看起來不太美觀,我想給直方柱子添加一個邊界線
plt.hist(height,bins=30,density=True,range=(180,200),edgecolor = 'k')
plt.show()
總結一下畫直方圖的步驟。
plt.figure(figsize=(12,6),dpi=100) # 1、指定畫布大小
plt.hist(height,bins=30,density=True,range=(180,200),edgecolor = 'k',label='height') # 2、畫圖,畫直方圖
plt.xlabel('height') # 指定x軸說明
plt.ylabel('rate') # 指定y軸說明
plt.title('hist of height') # 指定圖像名字
plt.grid() # 生成網格
# plt.savefig('./plot_of_students_height.png') # 根據自己需求是否儲存圖像
plt.legend() # 顯示圖例,圖例包括圖示等
plt.show() # 展示圖檔
接下來,畫散點圖。觀看身高和體重的關系。從圖像中的資料來看,資料完全是随機的,因為我們原始資料就是随機的。
plt.scatter(height,weight)
plt.show()
同理,如果有需要,可以在一張畫布圖像中多畫幾個散點圖
plt.scatter(height,weight)
plt.scatter(old,grade)
plt.show()
除了模型的形式,我們還可以改變散點圖點的透明度
plt.scatter(height,weight,alpha = 0.5)
plt.show()
同樣,我們整理一下散點圖的全部流程。
plt.figure(figsize=(12,6),dpi=100) # 1、指定畫布大小
plt.scatter(height,weight,alpha = 0.5) # 2、畫圖,畫散點圖
plt.xlabel('height') # 指定x軸說明
plt.ylabel('weight') # 指定y軸說明
plt.title('scatter of height and weight') # 指定圖像名字
plt.grid() # 生成網格
# plt.savefig('./plot_of_students_height.png') # 根據自己需求是否儲存圖像
# plt.legend() # 顯示圖例,圖例包括圖示等
plt.show() # 展示圖檔
接下來我們看一下最簡單的餅圖如何繪制
data = [2,5,8,13,7]
plt.pie(data)
plt.show()
上面的餅圖沒有靈魂,一來沒有圖示,二來沒有資料,讓我們把需要的要素添加進來
data = [2,5,8,13,7]
plt.pie(data,
labels = ['apple','banane','gredd','egg','compt'], # 指定每一類的标簽
)
plt.show()
然後我想把所占比例的大小也在圖像中展現出來
data = [2,5,8,13,7]
plt.pie(data,
labels = ['apple','banane','gredd','egg','compt'], # 指定每一類的标簽
autopct='%1.1f%%',
)
plt.show()
到這裡感覺這個餅圖就差不多有模有樣了,現在也将例子總結一下
plt.figure(figsize=(12,6),dpi=100) # 1、指定畫布大小
data = [2,5,8,13,7]
plt.pie(data,
labels = ['apple','banane','gredd','egg','compt'], # 指定每一類的标簽
autopct='%1.1f%%',
)
# plt.xlabel('height') # 指定x軸說明,餅圖沒有x軸
# plt.ylabel('weight') # 指定y軸說明,餅圖沒有y軸
plt.title('pie of data') # 指定圖像名字
# plt.grid() # 生成網格,餅圖沒有表格
# plt.savefig('./plot_of_students_height.png') # 根據自己需求是否儲存圖像
# plt.legend() # 顯示圖例,圖例包括圖示等
plt.show() # 展示圖檔
接下來看一下最簡單的箱形圖如何繪制
plt.boxplot(height)
plt.show()
初看,好簡單呀,二看,這是啥東西,三看,我們還是來看一下什麼是箱線圖吧。
箱線圖一般用來展現資料的分布(如上下四分位值、中位數等),同時,也可以用箱線圖來反映資料的異常情況。
為了美觀,給箱體填充顔色,
plt.boxplot(height,patch_artist=True)
plt.show()
為了更加清晰,我給箱體中均值的位置切一個口,這樣就更加好看了
plt.boxplot(height,patch_artist=True,notch=True)
plt.show()
我還想一次性将身高、體重、年齡、成績四種資料一次性畫在一張圖上面,怎麼辦呢,先來個反面教材
plt.boxplot(height,patch_artist=True,notch=True)
plt.boxplot(weight,patch_artist=True,notch=True)
plt.show()
plt.boxplot(height,patch_artist=True,notch=True)
plt.boxplot(weight,patch_artist=True,notch=True)
plt.boxplot(old,patch_artist=True,notch=True)
plt.show()
正常人都可以看出來,這樣太醜了,也不能很好展現出資料的情況,是以我們換種方式畫,添加一個變量vert=True
plt.boxplot([height,weight,old,grade],patch_artist=True,notch=True,vert=True)
plt.show()
因為身高、體重、年齡、成績的量綱都不一樣,工作中不會将資料進行這樣的對較。
真正會比較的情景是四個店鋪一年内每日的銷售額,這種拿來比較是合适的
接下來看一下柱狀圖的最簡單繪制,展示五個學生每個人擁有的朋友的個數。
friends = [2,5,8,13,7]
plt.bar(['Npo','Xiaoming','Jomo','Elosi','Jenbo'],friends)
plt.show()
如果我還想将這五位同學家裡兄弟姐妹的人數也畫在同一副畫裡面,該怎麼畫呢
friends = [2,5,8,13,7]
famrily = [1,4,3,2,5]
plt.bar(np.arange(len(friends)), friends, tick_label=['Npo','Xiaoming','Jomo','Elosi','Jenbo'],width = 0.35,label='friends')
plt.bar(np.arange(len(famrily))+0.35, famrily, tick_label=['Npo','Xiaoming','Jomo','Elosi','Jenbo'],width = 0.35,label='famrily')
plt.legend()
plt.show()
現在畫的是橫軸的柱狀圖,怎麼畫豎軸的柱狀圖呢。隻需将bar函數變成barh函數即可
friends = [2,5,8,13,7]
plt.barh(['Npo','Xiaoming','Jomo','Elosi','Jenbo'],friends)
plt.show()
最後補充一點如何繪制子圖,當我們需要同時呈現資料的時候很有用,繪制子圖的架構如下:
fig = plt.figure(figsize=(12,6),dpi=100) # 第一步,建立畫布
ax = fig.add_subplot(2,2,1) # 指定子圖,(第二步,指定子圖),接下去就會繪制了
ax.plot(height)
ax.set_xlabel('student') # 設定x軸的标注
ax.set_ylabel('height') # 設定y軸的标注
ax.set_title('height') # 設定圖像的名字
ax1 = fig.add_subplot(2,2,2) # 指定子圖
ax1.plot(old)
ax1.set_xlabel('student')
ax1.set_ylabel('old')
ax1.set_title('old')
ax2 = fig.add_subplot(2,1,2) # 指定子圖
ax2.plot(weight)
ax2.set_xlabel('student')
ax2.set_ylabel('weight')
ax2.set_title('weight')
plt.show()
接下來展示一個繪制堆疊圖的例子,先看一下最簡單的堆疊圖是什麼樣子的。
堆疊圖用于顯示『部分對整體』随時間的關系。 堆疊圖基本上類似于餅圖,隻是随時間而變化。
讓我們考慮一個情況,我們一天有 24 小時,我們睡覺,吃飯,工作和玩耍的時間如下所示
days = [1,2,3,4,5]
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [8,5,7,8,13]
plt.stackplot(days, sleeping,eating,working,playing)
plt.show()
這樣看的話,我們看不清楚哪一塊區域屬于哪個活動,是以我們需要添加圖示。
plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)
plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])
plt.legend()
plt.show()