共12個章節(jié),
本文為第1~4章節(jié)。
1 準備工作
1.1 Matplotlib安裝
1.2 Matplotlib版本查看
1.3 Matplotlib默認參數(shù)設置
2、散點圖
2.1 默認散點圖
2.2 散點圖點大小、顏色設置
2.3 散點圖標記、點動態(tài)變化
2.4 散點圖colormap、透明度設置
3、折線圖
3.1 默認折線圖
3.2 折線圖線型、分面設置
3.3 折線圖線寬設置
3.4 折線圖標記設置
3.5 折線圖多標記、標記間距設置
3.6 折線圖誤差線設置
3.7 折線圖僅保留誤差線
3.8 折線圖填充設置
3.9 折線圖添加垂直線
3.10 折線圖添加垂直平面
4、直方圖
4.1 默認直方圖
4.2 直方圖bins數(shù)設置
4.3 直方圖配色、軸范圍設置
4.4 水平直方圖
4.5 直方圖bins添加邊界線
4.6 多組直方圖
4.7 直方圖修改箱子透明度
4.8 更多組直方圖
4.9 2D直方圖
4.10 2D直方圖修改bins數(shù)
4.11 2D直方圖定義colormap
4.12 2D直方圖顯示范圍內(nèi)變量
4.13 邊界直方圖
#方法1 使用pip安裝
pip install matplotlib
#方法2 使用conda安裝
conda install matplotlib
Matplotlib版本查看,
# matplotlib版本查看
pip show matplotlib
# 默認參數(shù)設置
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 15 #設置字號
plt.rcParams['font.family'] = 'serif' #設置字體
tdir = 'out'
major = 5.0
minor = 3.0
plt.rcParams['xtick.direction'] = tdir #x軸刻度線朝外,PS刻度線為數(shù)字與坐標軸之間的連線
plt.rcParams['ytick.direction'] = tdir #y軸刻度線朝外
plt.rcParams['xtick.major.size'] = major #x軸主刻度線長度
plt.rcParams['xtick.minor.size'] = minor #x軸副刻度線長度
plt.rcParams['ytick.major.size'] = major #y軸主刻度線長度
plt.rcParams['ytick.minor.size'] = minor #y軸副刻度線長度
默認參數(shù)設定后,后續(xù)繪圖涉及以上參數(shù)的地方都采用此處值。
該部分通過散點圖介紹Matplotlib使用。
繪圖數(shù)據(jù)準備,
#準備繪圖數(shù)據(jù)
import numpy as np # 導入依賴numpy
import matplotlib.pyplot as plt #導入matplotlib
N = 50
x = np.linspace(0., 10., N) #x變量數(shù)據(jù):使用numpy生成長度為50的數(shù)組,范圍在1~10之間
y = np.sin(x)**2 + np.cos(x) #y變量數(shù)據(jù):基與x生成y
x,y變量預覽,
plt.figure() #figure生成一幅Figure
plt.scatter(x, y) #scatter函數(shù)繪制散點圖
下面對點大小固定變化、顏色、圖例進行調(diào)整以美化圖形,
plt.figure()
plt.scatter(x, y, s=15, label=r'$ y = sin^2(x) + cos(x), color='r')
#s設置點的大小
#label設置圖例名稱
#color設置點顏色
plt.axis('equal') #x軸和y軸單位長度相同。還有一個plt.axis('square')將x軸和y軸長度設置相等,即圖是正方形。
plt.legend() # 開啟圖例
plt.xlabel(r'$x$ (rad)') # 設置x軸標題
plt.ylabel(r'$y) # 設置y軸標題
plt.show() #圖形渲染/展示
設置圖形分辨率、點marker、點大小動態(tài)變化,更多marker修改??一文掌握marker使用
plt.figure(dpi=100) #設置圖形分辨率,控制圖形清晰度
plt.scatter(
x,
y,
s=x, #點大小隨變量x大小變化
marker='^', #設置點的marker為三角形
label=r'$ y = sin^2(x) + cos(x),
color='r')
plt.axis('equal')
plt.legend()
plt.xlabel(r'$x$ (rad)')
plt.ylabel(r'$y)
plt.show()
設置點顏色動態(tài)變化、設置點colormap、透明度,了解詳細顏色設置??$y)
plt.colorbar() #添加colorbar
plt.show()
該部分通過折線圖介紹Matplotlib使用。
#準備繪圖數(shù)據(jù)
N = 50
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
#散點圖繪制
plt.plot(x, y)
plt.show()
修改折線圖線型、分面展示,
N = 50
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
rows = 2
columns = 2
grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)
#分面為4張圖展示不同線型,分面此處使用GridSpec()方法
#還可以使用subplot()、add_subplot()方法
linestyles = ['-', '--', '-.', ':']
plt.figure(dpi=120)
for i in range(len(linestyles)):
plt.subplot(grid[i])
plt.plot(
x,
y,
linestyle=linestyles[i], #linestyle設置線型
label=r'$ y = sin^2(x) + cos(x))
plt.axis('equal')
plt.xlabel('$x$ (rad)')
plt.legend()
#添加文字注釋
plt.annotate('linestyle '' + str(linestyles[i]) + ''',
xy=(0.5, -2.5),
va='center',
ha='left')
修改折線圖線寬,
N = 50
rows = 2
columns = 2
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)
linewidth = [2, 3, 4, 5]
plt.figure(dpi=150)
for i in range(len(linestyles)):
plt.subplot(grid[i])
plt.plot(
x,
y,
linestyle='-.',
lw=linewidth[i], #lw設置線寬
label=r'$ y = sin^2(x) + cos(x))
plt.axis('equal')
plt.xlabel('$x$ (rad)')
plt.legend()
plt.annotate('linewidth ' + str(linewidth[i]),
xy=(0.5, -2.5),
va='center',
ha='left')
折線圖添加marker,
N = 50
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
plt.figure(dpi=150)
plt.plot(
x,
y,
'o',
ls='-.',
lw=2,
ms=7, #marker大小
markevery=12, #每隔12個點添加marker
label=r'$ y = sin^2(x) + cos(x))
plt.axis('equal')
plt.xlabel('$x$ (rad)')
plt.legend()
plt.annotate('markevery: 5', xy=(0.5, -2.5), va='center', ha='left')
不同折線圖添加不同marker、按照不同的間距,
N = 50
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
rows = 2
columns = 2
grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)
mark = [5, 8, 13, 15]
color = ['#00429d', '#627c94', '#f4777f', '#93003a']
plt.figure(dpi=150)
for i in range(len(linestyles)):
plt.subplot(grid[i])
plt.plot(
x,
y,
'o',
ls='-.',
lw=2,
ms=8,
markevery=mark[i], #不同間隔
color=color[i], #不同顏色
label=r'$ y = sin^2(x) + cos(x))
plt.axis('equal')
plt.annotate('markevery: ' + str(mark[i]),
xy=(0.5, -2.5),
va='center',
ha='left')
plt.xlabel('$x$ (rad)')
plt.legend()
折線圖添加誤差線,
N = 25
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
np.random.seed(100)
noise_x = np.random.random(N) * .2 + .1
noise_y = np.random.random(N) * .7 + .4
plt.figure(dpi=120)
#使用errorbar方法添加誤差線
plt.errorbar(
x,
y,
yerr=noise_y, #y軸方向添加誤差線
xerr=noise_x, #x軸方向添加誤差線
label=r'$ y = sin^2(x) + cos(x))
plt.axis('equal')
plt.legend()
plt.xlabel('$x$ (rad)')
去掉折線,只保留誤差線,
N = 25
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
np.random.seed(100)
noise_x = np.random.random(N) * .2 + .1
noise_y = np.random.random(N) * .7 + .4
plt.figure(dpi=150)
plt.errorbar(
x,
y,
xerr=noise_x,
yerr=noise_y,
label=r'$ y = sin^2(x) + cos(x),
color='r', #marker顏色
fmt='o', #marker形狀
ecolor='blue', #誤差線顏色
)
plt.axis('equal')
plt.legend()
plt.xlabel('$x$ (rad)')
折線圖區(qū)域填充,
N = 25
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
np.random.seed(100)
noise = np.random.random(N) * .7 + .4
plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y = sin^2(x) + cos(x))
#使用fill_between方法
plt.fill_between(
x,
y + noise, #y軸上方區(qū)域
y - noise, #y軸下方區(qū)域
alpha=.3)
plt.axis('equal')
plt.legend()
plt.xlabel('$x$ (rad)')
添加x軸、y軸方向垂直線,
N = 25
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
np.random.seed(100)
noise = np.random.random(N) * .7 + .4
plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y = sin^2(x) + cos(x), color='darkgreen')
plt.fill_between(x, y + noise, y - noise, color='darkgreen', alpha=.3)
plt.axis('equal')
#hlines繪制水品線
plt.hlines(
0, #y軸位置
xmin=0, #x軸起始位置
xmax=10, #x軸終止位置
ls='--', #線型
color='red', #線顏色
label='hlines') #圖例
#hlines繪制垂直線
plt.vlines(2, ymin=-3, ymax=3, ls='--', color='blue', label='vlines')
plt.legend()
plt.xlabel('$x$ (rad)')
添加y軸方向垂直平面,
N = 25
x = np.linspace(0., 10., N)
y = np.sin(x)**2 + np.cos(x)
np.random.seed(100)
noise = np.random.random(N) * .7 + .4
plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y = sin^2(x) + cos(x), color='darkgreen')
plt.fill_between(x, y + noise, y - noise, color='darkgreen', alpha=0.3)
plt.axis('equal')
plt.fill_between((2, 4), -3.2, 3.2, facecolor='blue', alpha=0.3)
plt.xlim(0, 10)
plt.ylim(-3, 3)
plt.legend()
plt.xlabel('$x$ (rad)')
該部分通過直方圖介紹Matplotlib使用。
N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.hist(x)
修改分箱bins數(shù)目。
N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.figure(dpi=120)
plt.hist(
x,
bins=40, #設置bins數(shù)目為40個
label=r'$\mu = 15, \sigma = 2 #添加圖例
)
plt.legend()
修改配色、橫軸顯示范圍。
N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.figure(dpi=120)
plt.hist(x,
bins=40,
range=(12, 18),#設置橫軸顯示范圍
color='pink', #修改配色
label=r'$\mu = 15, \sigma = 2)
plt.legend()
繪制水平方向直方圖。
N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.figure(dpi=120)
plt.hist(
x,
bins=25,
range=(12, 18),
color='royalblue',
orientation='horizontal', #水平方向直方圖
label=r'$\mu = 15, \sigma = 2)
plt.legend()
為直方圖bins添加邊界線。
N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.figure(dpi=120)
plt.hist(
x,
bins=25,
range=(12, 18),
color='royalblue',
orientation='horizontal',
edgecolor='k', #bins邊界上色
label=r'$\mu = 15, \sigma = 2)
plt.legend()
N = 1000
mu1 = 5
mu2 = 10
mu3 = 15
sigma1 = 5
sigma2 = 3
sigma3 = 2
x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3
plt.figure(dpi=120)
plt.hist(
x1, #變量1
bins=30,
color='royalblue',
label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1))
plt.hist(
x2, #變量2
bins=30,
color='tomato',
label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2))
plt.hist(
x3, #變量3
bins=30,
color='gray',
label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3))
plt.legend()
N = 1000
mu1 = 5
mu2 = 10
mu3 = 15
sigma1 = 5
sigma2 = 3
sigma3 = 2
x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3
plt.figure(dpi=120)
plt.hist(x1,
bins=30,
color='royalblue',
label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1),
alpha=.7 #透明度通過alpha設置
)
plt.hist(x2,
bins=30,
color='tomato',
label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2),
alpha=.7)
plt.hist(x3,
bins=30,
color='gray',
label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3),
alpha=.7)
plt.legend()
N = 1000
mu1 = 5
mu2 = 10
mu3 = 15
sigma1 = 5
sigma2 = 3
sigma3 = 2
x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3
mu = np.array([mu1, mu2, mu3])
sigma = np.array([sigma1, sigma2, sigma3])
x = np.array([x1, x2, x3])
colors = ['royalblue', 'tomato', 'gray']
plt.figure(dpi=120)
#循環(huán)方式繪圖
for i in range(len(x)):
plt.hist(x[i], bins = 30, color = colors[i],
label = r'$\mu = $ ' + str(mu[i]) +
', $\sigma = $ ' + str(sigma[i]), alpha = .7)
plt.legend()
通過循環(huán),我們可以一圖繪制更多直方圖。
N_func = 10
N_data = 1000
np.random.seed(1000)
mu = np.random.randint(low=-5, high=5, size=N_func)
sigma = np.random.randint(low=1, high=5, size=N_func)
x = []
for i in range(len(mu)):
xi = np.random.randn(N_data) * sigma[i] + mu[i]
x.append(xi)
colors = [
'#00429d', '#7f40a2', '#a653a1', '#c76a9f', '#e4849c', '#d0e848',
'#b6cf54', '#a9b356', '#b2914b', '#ff0001'
]
plt.figure(dpi=120)
for i in range(len(mu)):
plt.hist(x[i],
bins=30,
color=colors[i],
label=r'$\mu = $ ' + str(mu[i]) + ', $\sigma = $ ' +
str(sigma[i]),
alpha=.7)
plt.legend(bbox_to_anchor=(1.33, 1.03))
N = 1_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.hist2d(x, y) #2D直方圖需要傳入兩個變量
N = 1_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.hist2d(x, y, bins=(25, 25)) #2D直方圖修改bins也需要傳入兩個變量
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
top = cm.get_cmap('Oranges_r', 128)
bottom = cm.get_cmap('Blues', 128)
newcolors = np.vstack((top(np.linspace(0, 1,
128)), bottom(np.linspace(0, 1, 128))))
orange_blue = ListedColormap(newcolors, name='OrangeBlue') #自定義colormap
N = 10_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.figure(dpi=120)
plt.hist2d(
x,
y,
bins=(75, 75),
cmap=orange_blue #傳入colormap
)
cb = plt.colorbar()
cb.set_label('counts each bin', labelpad=10)
N = 10_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.figure(dpi=120)
plt.hist2d(x, y, bins=(75, 75), cmap='jet',
cmin=5, cmax=25 #定義
)
cb = plt.colorbar()
cb.set_label('counts each bin', labelpad=10)
N = 10_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
rows = 5
columns = 5
grid = plt.GridSpec(rows, columns, wspace=.4, hspace=.4)
plt.figure(dpi=120)
plt.subplot(grid[0, 0:-1])
plt.hist(x, bins=40, color='royalblue', alpha=.6)
plt.annotate('Normal 1', xy=(2, 500), va='center', ha='left')
plt.subplot(grid[1:rows + 1, 0:-1])
plt.hist2d(x, y, cmap='Blues', bins=(30, 40))
plt.axis('equal')
plt.subplot(grid[1:rows + 1, -1])
plt.hist(y, bins=40, orientation='horizontal', color='royalblue', alpha=.6)
plt.annotate('Normal 2', xy=(500, 2), va='bottom', ha='center', rotation=-90)