入门matplotlib绘图【完整版】
做數據分析的時候,自己繪制圖像的時候總是遇到各種想不起來的代碼,總是需要去查,我覺得自己總結一下python的繪圖手法,對后面自己能力的構建會很有幫助。
本片總結涉及到的matplotlib繪圖的基礎內容包括:走勢圖(也稱折線圖),直方圖,餅圖,散點圖,柱狀圖,條形圖,堆疊圖,以及圖標、圖例、子圖和保存圖像的使用方法
繪圖之前需要構建一些數據,下面隨機構建一群學生的身高、體重、年齡、語文成績的數據
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random 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()我們在這里做的是畫一些空行,給予它們符合我們的堆疊圖的相同顏色,和正確標簽。
我們還使它們線寬為 5,使線條在圖例中顯得較寬。 現在,我們可以很容易地看到,我們如何花費我們的時間。
從圖中一目了然看出,工作時間五天一來,時間越來越少,反而娛樂的時間越來越多。
覺得有用的話,給我點個贊吧!
總結
以上是生活随笔為你收集整理的入门matplotlib绘图【完整版】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android,按钮按下抬起背景,不需要
- 下一篇: 10.26 T3.蚊子(mosquito