matplotlib的使用
點擊標題即可獲取文章源代碼和筆記
二、Matplotlib
2.1 Matplotlib之HelloWorld
2.1.1 什麼是Matplotlib - 畫二維圖表的python庫
mat - matrix 矩陣
二維數據 - 二維圖表
plot - 畫圖
lib - library 庫
matlab 矩陣實驗室
mat - matrix
lab 實驗室
2.1.2 爲什麼要學習Matplotlib - 畫圖
數據可視化 - 幫助理解數據,方便選擇更合適的分析方法
js庫 - D3 echarts
奧卡姆剃刀原理 - 如無必要勿增實體
2.1.3 實現一個簡單的Matplotlib畫圖
2.1.4 認識Matplotlib圖像結構
2.1.5 拓展知識點:Matplotlib三層結構
1)容器層
畫板層Canvas
畫布層Figure
繪圖區/座標系
x、y軸張成的區域
2)輔助顯示層
3)圖像層
2.2 折線圖(plot)與基礎繪圖功能
2.2.1 折線圖繪製與保存圖片
3 設置畫布屬性與圖片保存
figsize : 畫布大小
dpi : dot per inch 圖像的清晰度
3 中文顯示問題解決
mac的一次配置,一勞永逸
ubantu每創建一次新的虛擬環境,需要重新配置
windows
1)安裝字體
mac/wins:雙擊安裝
ubantu:雙擊安裝
2)刪除matplotlib緩存文件
3)配置文件
2.2.4 多個座標系顯示-plt.subplots(面向對象的畫圖方法)
figure, axes = plt.subplots(nrows=1, ncols=2, **fig_kw)
axes[0].方法名()
axes[1]
2.2.5 折線圖的應用場景
某事物、某指標隨時間的變化狀況
拓展:畫各種數學函數圖像
2.3.1 常見圖形種類及意義
折線圖plot
散點圖scatter
關係/規律
柱狀圖bar
統計/對比
直方圖histogram
分佈狀況
餅圖pie π
佔比
2.3.2 散點圖繪製
2.4 柱狀圖(bar)
2.4.1 柱狀圖繪製
2.5 直方圖(histogram)
2.5.1 直方圖介紹
組數:在統計數據時,我們把數據按照不同的範圍分成幾個組,分成的組的個數稱爲組數
組距:每一組兩個端點的差
已知 最高175.5 最矮150.5 組距5
求 組數:(175.5 - 150.5) / 5 = 5
2.5.2 直方圖與柱狀圖的對比
1. 直方圖展示數據的分佈,柱狀圖比較數據的大小。
2. 直方圖X軸爲定量數據,柱狀圖X軸爲分類數據。
3. 直方圖柱子無間隔,柱狀圖柱子有間隔
4. 直方圖柱子寬度可不一,柱狀圖柱子寬度須一致
2.5.3 直方圖繪製
x = time
bins 組數 = (max(time) - min(time)) // 組距
3 直方圖注意點
2.6 餅圖(pie)
%1.2f%%
print("%1.2f%%")
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure()
plt.plot([1,2,3,4,5,6,7],[17,17,18,15,11,11,13])
plt.show()
折線圖繪製與顯示
#展示上海一週的天氣,比如從星期一到星期日的天氣溫度如下
# 1. 創建畫布
# figsize:指定圖片的長寬
# dpi:指定圖像的清晰度
plt.figure(figsize=(20,8),dpi=280)
# 2. 繪製圖像
plt.plot([1,2,3,4,5,6,7],[17,17,18,15,11,11,13])
# 保存圖像
plt.savefig("fig01.png")
# 3. 顯示圖像
plt.show()
- 注意:plt.show()會釋放figure資源,如果在顯示圖像之後保存圖片,將只能保存空白的圖片
案例:顯示溫度變化情況(輔助顯示層)
需求:畫出某城市11點到12點1小時內每分鐘的溫度變化折線圖,溫度範圍在15度~18度
import random
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_shanghai
[16.762333158978358,
16.943581178301798,
17.21289155110738,
17.304877451487915,
16.498088429709327,
...
15.54547871676703,
17.524143671682424,
17.978133652214485,
17.370197846502908]
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 4. 顯示圖像
plt.show()
2.添加自定義x,y刻度
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 修改x,y刻度
plt.xticks(range(0,60,5))
plt.yticks(range(0,40,5))
# 4. 顯示圖像
plt.show()
["11點{}分".format(i) for i in range(61)]
['11點0分',
'11點1分',
'11點2分',
'11點3分',
'11點4分',
'11點5分',
'11點6分',
...
'11點56分',
'11點57分',
'11點58分',
'11點59分',
'11點60分']
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 4. 顯示圖像
plt.show()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 28857 missing from current font.
font.set_text(s, 0.0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20998 missing from current font.
font.set_text(s, 0.0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 28857 missing from current font.
font.set_text(s, 0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20998 missing from current font.
font.set_text(s, 0, flags=flags)
3.解決中文顯示問題
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 4. 顯示圖像
plt.show()
4. 添加網格顯示
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 添加網格顯示
# grid(是否顯示網格,網格線樣式,網格透明度)
plt.grid(True,linestyle="--",alpha=0.5)
# 4. 顯示圖像
plt.show()
5.添加描述信息
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai)
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 添加描述信息
plt.xlabel("時間")
plt.ylabel("溫度")
plt.title("某城市中午11:00到12:00zip間的溫度變化圖示")
# 添加網格顯示
# grid(是否顯示網格,網格線樣式,網格透明度)
plt.grid(True,linestyle="--",alpha=0.5)
# 4. 顯示圖像
plt.show()
再添加一個城市的溫度變化(圖像層)
收集到北京當天溫度變化情況,溫度在1度到3度。
y_beijing = [random.uniform(1,3) for i in range(61)]
y_beijing
[2.6582522879775263,
1.2944662118583519,
2.9128902882809036,
2.3066941253832427,
2.100357799277068,
...
1.0759520914191576,
1.3613792689673339,
2.0180224854714215,
2.042084118916457,
2.8643212857317306]
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai,color='r',linestyle="--")
plt.plot(x,y_beijing,color='b')
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 添加描述信息
plt.xlabel("時間")
plt.ylabel("溫度")
plt.title("上海、北京中午11:00到12:00zip間的溫度變化圖示")
# 添加網格顯示
# grid(是否顯示網格,網格線樣式,網格透明度)
plt.grid(True,linestyle="--",alpha=0.5)
# 4. 顯示圖像
plt.show()
顯示圖例
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]
# 2. 創建畫布
plt.figure(figsize=(22,8),dpi=100)
# 3. 繪製圖像
plt.plot(x,y_shanghai,color='r',linestyle="--",label="上海")
plt.plot(x,y_beijing,color='b',label="北京")
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))
# 添加描述信息
plt.xlabel("時間")
plt.ylabel("溫度")
plt.title("上海、北京中午11:00到12:00zip間的溫度變化圖示")
# 添加網格顯示
# grid(是否顯示網格,網格線樣式,網格透明度)
plt.grid(True,linestyle="--",alpha=0.5)
# 顯示圖例
plt.legend(loc="best")
# plt.legend(loc=2)
# 4. 顯示圖像
plt.show()
多個座標系顯示-plt.subplots(面向對象的畫圖方法)
我們想要將上海和北京的天氣圖顯示在同一個圖的不同座標系當中
import random
# 1. 準備數據 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]
# 2. 創建畫布
# plt.figure(figsize=(22,8),dpi=100)
# figure是畫布對象,axes是繪圖區對象
figure,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,8),dpi=80)
# 3. 繪製圖像
axes[0].plot(x,y_shanghai,color='r',linestyle="--",label="上海")
axes[1].plot(x,y_beijing,color='b',label="北京")
# 修改x,y刻度
# 準備x的刻度說明
x_label = ["11點{}分".format(i) for i in range(61)]
axes[0].set_xticks(range(0,60,7)) # 設置x軸刻度大小
axes[0].set_xticklabels(x_label[::7]) # 設置x軸每個刻度的名字
axes[1].set_yticks(range(0,40,7))
axes[1].set_xticklabels(x_label[::7])
# 添加描述信息
axes[0].set_xlabel("時間")
axes[0].set_ylabel("溫度")
axes[0].set_title("上海中午11:00到12:00zip間的溫度變化圖示")
axes[1].set_xlabel("時間")
axes[1].set_ylabel("溫度")
axes[1].set_title("北京中午11:00到12:00zip間的溫度變化圖示")
# 添加網格顯示
# grid(是否顯示網格,網格線樣式,網格透明度)
axes[0].grid(True,linestyle="--",alpha=0.5)
axes[1].grid(True,linestyle="--",alpha=0.5)
# 顯示圖例
axes[0].legend(loc="best")
axes[1].legend(loc="best")
# plt.legend(loc=2)
# 4. 顯示圖像
plt.show()
數學函數圖像
import numpy as np
# 1. 準備數據
x = np.linspace(-10,10,1000)
y = np.sin(x)
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製函數圖像
plt.plot(x,y)
# 添加網格顯示
plt.grid()
# 4. 顯示圖像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>
import numpy as np
# 1. 準備數據
x = np.linspace(-10,10,1000)
y = np.cos(x)
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製函數圖像
plt.plot(x,y)
# 添加網格顯示
plt.grid()
# 4. 顯示圖像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>
import numpy as np
# 1. 準備數據
x = np.linspace(-10,10,1000)
y = 2*x*x
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製函數圖像
plt.plot(x,y)
# 添加網格顯示
plt.grid(linestyle='--',alpha=0.5)
# 4. 顯示圖像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>
2.3.2散點圖繪製
需求:探究房屋面積和屋價格的關係
# 1. 準備數據
# 房屋面積數據
x=[225.98,247.07,253.14,457.85,241.58,301.01,20.67,288.64,163.56,120.86,207.83,342.75,147.9,53.06,224.72,29.51,21.61,483.21,245.25,399.25,343.35]
# 房屋價格數據
y=[196.63,203.88,210.75,372.74,202.41,247.61,24.9,239.34,148.32,104.15,176.84,288.23,128.79,49.64,191.74,33.1,30.74,400.02,205.35,330.64,283.45]
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製圖像
plt.scatter(x,y)
# 3. 顯示圖像
plt.show()
2.4 柱狀圖
需求1-對比每部電影的票房收入
# 1. 準備數據
movie_names = ['雷神3:諸神黃昏','正義聯盟','東方快車謀殺案','尋夢環遊記','全球風暴', '降魔傳','追捕','七十七天','密戰','狂獸','其它']
tickets = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222]
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製柱狀圖
x_ticks = range(len(movie_names))
plt.bar(x_ticks,tickets,color=['b','r','g','y','c','m','y','k','c'])
# 修改x的刻度值
# plt.xticks(刻度的大小,刻度上的值)
plt.xticks(x_ticks,movie_names)
# 添加標題
plt.title("電影票房收入對比")
# 添加網格
plt.grid(linestyle="--",alpha=0.5)
# 4. 顯示圖像
plt.show()
需求2-如何對比電影票房收入才更能加有說服力
比較相同天數的票房
有時候爲了公平起見,我們需要對比不同電影首日和首周的票房
# 1. 準備數據
movie_name=['雷神3:諸神黃昏','正義聯盟','尋夢環遊記']
first_day=[10587.6,10062.5,1275.71]
first_weekend=[36224.9,34479.6,11830]
x = range(len(movie_name))
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製柱狀圖
plt.bar(x,first_day,width=0.2,label="首日票房")
# [i+0.2 for i in x] 這是列表生成式
plt.bar([i+0.2 for i in x],first_weekend,width=0.2,label="首周票房")
# 顯示圖例
plt.legend(loc="best")
# 修改刻度
plt.xticks([i+0.1 for i in x],movie_name)
# 設置標題
plt.title("對比不同電影首日和首周的票房")
# 設置表格
plt.grid(linestyle="--",alpha=0.5)
# 4. 顯示圖像
plt.show()
2.5 直方圖(histogram)
·組數:在統計數據時,我們把數據按照不同的範圍分成幾個組,分成的組的個數稱爲組數
·組距:每一組兩個端點的差
直方圖 VS 柱狀圖:
1.直方圖展示數據的分佈,柱狀圖比較數據的大小
2.直方圖X軸爲定量數據,柱狀圖X軸爲分類數據。
3.直方圖柱子無間隔,柱狀圖柱子有間隔
- 因爲直方圖中的區間是連續的,因此柱子之間不存在間隙。而柱狀圖的柱子之間是存在間隔。
4.直方圖柱子寬度可不一,柱狀圖柱子寬度須一致
2.5.3 直方圖繪製
需求:電影時長分佈狀況
# 1、準備數據
time = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
# 2、創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3、給制直方圖
#通常設置組數會有相應公式:組數=極差/組距=(max-min)/組距
# plt.hist(x,組數)
distance = 2 # 組距
group_num = int((max(time)-min(time))/distance) # 組數
plt.hist(time,bins=group_num,density=True) # density=True 則y軸顯示的刻度值爲頻率,否則爲頻數
# 添加網格
plt.grid(linestyle="--", alpha=0.5)
# 添加標題
plt.title("電影時長分佈狀況")
# 修改x軸刻度
plt.xticks(range(min(time),max(time)+2,distance))
# 4、顯示圖倒
plt.show()
2.6.2餅圖繪製
需求:顯示不同的電影的排片佔比
# 1. 準備數據
movie_name = ['雷神3:諸神黃昏','正義聯盟','東方快車謀殺案','尋夢環遊記','全球風暴','降魔傳','追捕','七十七天','密戰','狂獸','其它']
place_count = [60605,54546,45819,28243,13270,9945,7679,6799,6101,4621,20105]
# 2. 創建畫布
plt.figure(figsize=(20,8),dpi=100)
# 3. 繪製餅圖
# autopct 顯示百分比的格式
plt.pie(place_count,labels=movie_name, colors=['b','r','g','y','c','m','y','k','c','g','y'], autopct="%1.2f%%")
# 添加axis
plt.axis("equal")
# 顯示圖例
plt.legend()
plt.title("不同的電影的排片佔比")
# 4. 顯示圖像
plt.show()