科研论文绘图实操干货汇总,11类Matplotlib图表,含代码
![](https://filescdn.proginn.com/96e541b89c406b37ed2c744aba19f538/27fc81addbf20bf46f44c5e344f27421.webp)
作者丨数据派THU
来源丨DataScience
编辑丨极市平台
极市导读
导读
numpy:1.18.5 pandas:1.0.5 matplotlib:3.2.1
1.简单的折线图
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
fig = plt.figure()
ax = plt.axes()
![](https://filescdn.proginn.com/2e23d785fa935884edec608d9e426867/a01b91b96a76e1380e9bdccbea563232.webp)
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));
![](https://filescdn.proginn.com/25ed6f0841538fee39a093631c270529/059524b826ce738c57c1ca806e061838.webp)
plt.plot(x, np.sin(x));
![](https://filescdn.proginn.com/25ed6f0841538fee39a093631c270529/059524b826ce738c57c1ca806e061838.webp)
plot
函数即可:plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x));
![](https://filescdn.proginn.com/7329cd3e83eedf52f100f559a174f2d4/c4522e9e5e082ee7c9e8bf48ef6d67b2.webp)
调整折线图:线条颜色和风格
plt.plot(x, np.sin(x - 0), color='blue') # 通过颜色名称指定
plt.plot(x, np.sin(x - 1), color='g') # 通过颜色简写名称指定(rgbcmyk)
plt.plot(x, np.sin(x - 2), color='0.75') # 介于0-1之间的灰阶值
plt.plot(x, np.sin(x - 3), color='#FFDD44') # 16进制的RRGGBB值
plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB元组的颜色值,每个值介于0-1
plt.plot(x, np.sin(x - 5), color='chartreuse'); # 能支持所有HTML颜色名称值
![](https://filescdn.proginn.com/1fe9523a096127ab7d408fe1a166e7ed/42232dabe88bc3817d117a9ec9e19b58.webp)
如果没有指定颜色,Matplotlib 会在一组默认颜色值中循环使用来绘制每一条线条。
plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted');
# 还可以用形象的符号代表线条风格
plt.plot(x, x + 4, linestyle='-') # 实线
plt.plot(x, x + 5, linestyle='--') # 虚线
plt.plot(x, x + 6, linestyle='-.') # 长短点虚线
plt.plot(x, x + 7, linestyle=':'); # 点线
![](https://filescdn.proginn.com/db585390dad56b07b813820ebd0ef169/09bd70c6fc6531040d6c244ffe9ecca3.webp)
plt.plot(x, x + 0, '-g') # 绿色实线
plt.plot(x, x + 1, '--c') # 天青色虚线
plt.plot(x, x + 2, '-.k') # 黑色长短点虚线
plt.plot(x, x + 3, ':r'); # 红色点线
![](https://filescdn.proginn.com/5a724fb61d62db6b049cda9de86c376e/a4e12cef2d5fa45ec1662d222ab0c479.webp)
调整折线图:坐标轴范围
plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);
![](https://filescdn.proginn.com/50034640bfdc9266cdcc3705704bd65d/b9324e39bd069e79338190325bce7f99.webp)
plt.plot(x, np.sin(x))
plt.xlim(10, 0)
plt.ylim(1.2, -1.2);
![](https://filescdn.proginn.com/ec5a44bf972ec380bd24776b3c1aff97/f4c315fb8e4cf859d85c8dd7d5203b7a.webp)
plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5]);
![](https://filescdn.proginn.com/50034640bfdc9266cdcc3705704bd65d/b9324e39bd069e79338190325bce7f99.webp)
plt.plot(x, np.sin(x))
plt.axis('tight');
![](https://filescdn.proginn.com/25ed6f0841538fee39a093631c270529/059524b826ce738c57c1ca806e061838.webp)
plt.plot(x, np.sin(x))
plt.axis('equal');
![](https://filescdn.proginn.com/5dc87dd5c4ae54ba2cf2fc794d71b617/63dc4fff6d5fed74ecd9dd8062bea774.webp)
折线图标签
plt.plot(x, np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");
![](https://filescdn.proginn.com/7f431de364f292a1829353a3af0eb0ae/e9fe6599ce3f5bfe347504d270a6de7d.webp)
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')
plt.legend();
![](https://filescdn.proginn.com/5d7d83fac4c6cca2d703e58e7f7e8ff4/a3db78642a81240a1f5fd435b66220bb.webp)
plt.xlabel() → ax.set_xlabel() plt.ylabel() → ax.set_ylabel() plt.xlim() → ax.set_xlim() plt.ylim() → ax.set_ylim() plt.title() → ax.set_title()
ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2),
xlabel='x', ylabel='sin(x)',
title='A Simple Plot');
![](https://filescdn.proginn.com/530f874bf5558b689d53b0d3cda4e4d4/98a9112530f4e16fb0f3b90762337021.webp)
2.简单散点图
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
使用 plt.plot 绘制散点图
x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o', color='black');
![](https://filescdn.proginn.com/b21c9c2704fcabc88634e5c2e7f6e724/b3d6df2784dc32d5930a813f496a5ed8.webp)
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt.plot(rng.rand(5), rng.rand(5), marker,
label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);
![](https://filescdn.proginn.com/acb86b437dd2e6c79ac5c9025d2e2f5d/f2713703925ff325c868b06cee9fb819.webp)
plt.plot(x, y, '-ok');
![](https://filescdn.proginn.com/6cefaa5c22611bb72a7049b73e53dc5c/c73b81bb44b9dbce9587fd7cf314bbe5.webp)
plt.plot(x, y, '-p', color='gray',
markersize=15, linewidth=4,
markerfacecolor='white',
markeredgecolor='gray',
markeredgewidth=2)
plt.ylim(-1.2, 1.2);
![](https://filescdn.proginn.com/1c6054448fae0f9e36c8fdba5aa36c51/a47602c92640172c4de8d32017ddfa22.webp)
使用plt.scatter绘制散点图
plt.scatter(x, y, marker='o');
![](https://filescdn.proginn.com/576fcaff9037732a44cb47fc6b5d77c8/a419ee6ef492311a6c7e681025e16502.webp)
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
cmap='viridis')
plt.colorbar(); # 显示颜色对比条
![](https://filescdn.proginn.com/0ee4aa137a1848e05ba9c25b7ad3a66b/a6287f2ba52e54fc65bff353315a03aa.webp)
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2,
s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1]);
![](https://filescdn.proginn.com/dfa7556c5307643eb3babc337b00630e/44fa3853472adc40cbf92c8637b6fe36.webp)
plot 和 scatter 对比:性能提醒
3.误差可视化
基础误差条
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x, y, yerr=dy, fmt='.k');
![](https://filescdn.proginn.com/9b5d4bea877b1d5c4e1b5f737b569ba3/2d74fd4aaff7ed327c122a96004e9283.webp)
plt.errorbar(x, y, yerr=dy, fmt='o', color='black',
ecolor='lightgray', elinewidth=3, capsize=0);
![](https://filescdn.proginn.com/f14616fc5e7b058d4304fb0231aff9f8/37d6cf5209feeabaac618de42f3dcf55.webp)
连续误差
from sklearn.gaussian_process import GaussianProcessRegressor
# 定义模型和一些符合模型的点
model = lambda x: x * np.sin(x)
xdata = np.array([1, 3, 5, 6, 8])
ydata = model(xdata)
# 计算高斯过程回归,使其符合 fit 数据点
gp = GaussianProcessRegressor()
gp.fit(xdata[:, np.newaxis], ydata)
xfit = np.linspace(0, 10, 1000)
yfit, std = gp.predict(xfit[:, np.newaxis], return_std=True)
dyfit = 2 * std # 两倍sigma ~ 95% 确定区域
# 可视化结果
plt.plot(xdata, ydata, 'or')
plt.plot(xfit, yfit, '-', color='gray')
plt.fill_between(xfit, yfit - dyfit, yfit + dyfit,
color='gray', alpha=0.2)
plt.xlim(0, 10);
![](https://filescdn.proginn.com/15c74caeedb56060933b8879ca0a8bba/5091989f1a20d3b9c2897c0fb8328643.webp)
4.密度和轮廓图
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
三维可视化函数
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contour(X, Y, Z, colors='black');
![](https://filescdn.proginn.com/38f860f7a7e0236fa6fa78cf0a125125/d4312797eb60af6662829935ce33a4d0.webp)
plt.contour(X, Y, Z, 20, cmap='RdGy');
![](https://filescdn.proginn.com/edad781135d200748da44944d17dd561/cf7a1b60a8f944f0d7ab6a6391b250bc.webp)
plt.cm.
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar();
![](https://filescdn.proginn.com/ffa44a5c5c2c41428728b880ace35636/47a25a202d67798b698d7c6d3af4c6fe.webp)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image');
C:\Users\gdc\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: MatplotlibDeprecationWarning: Passing unsupported keyword arguments to axis() will raise a TypeError in 3.3.
after removing the cwd from sys.path.
![](https://filescdn.proginn.com/c17b3e968395c7b66a5b736138c93981/7980cd5b54cd50759a4a9087b8f1840d.webp)
plt.imshow()不接受 x 和 y 网格值作为参数,因此你需要手动指定extent参数[xmin, xmax, ymin, ymax]来设置图表的数据范围。 plt.imshow()使用的是默认的图像坐标,即左上角坐标点是原点,而不是通常图表的左下角坐标点。这可以通过设置origin参数来设置。 plt.imshow()会自动根据输入数据调整坐标轴的比例;这可以通过参数来设置,例如,plt.axis(aspect='image')能让 x 和 y 轴的单位一致。
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();
![](https://filescdn.proginn.com/6305009960562e8a45170396ea742fd7/2a7e3381c3b122129407e7cdb5f03353.webp)
5.直方图,分桶和密度
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
data = np.random.randn(1000)
plt.hist(data);
![](https://filescdn.proginn.com/da303e1bce6efe56148d0dd1aa0218fd/11f1c9d7fefb2126662828515f317951.webp)
plt.hist(data, bins=30, density=True, alpha=0.5,
histtype='stepfilled', color='steelblue',
edgecolor='none');
![](https://filescdn.proginn.com/7be4190de09ee8eb4879b943045f404b/48261d53caa0026bc0af722648288ab6.webp)
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);
![](https://filescdn.proginn.com/e826ab8c14b37e41d115744ffac437b3/a94a8956767284ed74364d4a1fcfa369.webp)
counts, bin_edges = np.histogram(data, bins=5)
print(counts)
[ 49 273 471 183 24]
二维直方图和分桶
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d:二维直方图
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
![](https://filescdn.proginn.com/9af723d7ecbffc6452d72f09ce066e6d/4d25d156310fc0f4823249aadcdee59d.webp)
counts, xedges, yedges = np.histogram2d(x, y, bins=30)
plt.hexbin:六角形分桶
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')
![](https://filescdn.proginn.com/200eb1d13a24d673eac755278e895dfa/6cac965060a6ee4804f9337c1f060835.webp)
核密度估计
from scipy.stats import gaussian_kde
# 产生和处理数据,初始化KDE
data = np.vstack([x, y])
kde = gaussian_kde(data)
# 在通用的网格中计算得到Z的值
xgrid = np.linspace(-3.5, 3.5, 40)
ygrid = np.linspace(-6, 6, 40)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
Z = kde.evaluate(np.vstack([Xgrid.ravel(), Ygrid.ravel()]))
# 将图表绘制成一张图像
plt.imshow(Z.reshape(Xgrid.shape),
origin='lower', aspect='auto',
extent=[-3.5, 3.5, -6, 6],
cmap='Blues')
cb = plt.colorbar()
cb.set_label("density")
![](https://filescdn.proginn.com/343352306c34b4080fe80a7c8d976521/791d7b82a2962d1a37c3856fbfb1cbeb.webp)
6.自定义图标图例
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import numpy as np
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend();
![](https://filescdn.proginn.com/38f7c278b16f9c527d540a4d61d48631/87c793ff0a95e4567a15db9b160c932e.webp)
ax.legend(loc='upper left', frameon=False)
fig
![](https://filescdn.proginn.com/b7ed983bf76347b7c5a8530edc62950d/9caaba770e0a18b2d457cd84eb756290.webp)
ax.legend(frameon=False, loc='lower center', ncol=2)
fig
![](https://filescdn.proginn.com/8a5dc99699a188386a60090139d357af/7494c4ef462882378a30a7556bf9a56e.webp)
ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
fig
![](https://filescdn.proginn.com/197e6de472a92059db835a1f98f18d0d/ea984096d5d30481234c719e2391460d.webp)
选择设置图例的元素
y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
# lines是一个线条实例的列表
plt.legend(lines[:2], ['first', 'second']);
![](https://filescdn.proginn.com/f07f8779b51bc44b94e08f9b19088e7f/ff2fa3b5db0205c8c1a1269afca4efe6.webp)
plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')
plt.plot(x, y[:, 2:])
plt.legend(framealpha=1, frameon=True);
![](https://filescdn.proginn.com/f07f8779b51bc44b94e08f9b19088e7f/ff2fa3b5db0205c8c1a1269afca4efe6.webp)
散点大小的图例
import pandas as pd
cities = pd.read_csv(r'D:\python\Github学习材料\Python数据科学手册\data\california_cities.csv')
# 提取我们感兴趣的数据
lat, lon = cities['latd'], cities['longd']
population, area = cities['population_total'], cities['area_total_km2']
# 绘制散点图,使用尺寸代表面积,颜色代表人口,不带标签
plt.scatter(lon, lat, label=None,
c=np.log10(population), cmap='viridis',
s=area, linewidth=0, alpha=0.5)
plt.axis('scaled')
plt.xlabel('longitude')
plt.ylabel('latitude')
plt.colorbar(label='log$_{10}$(population)')
plt.clim(3, 7)
# 下面我们创建图例:
# 使用空列表绘制图例中的散点,使用不同面积和标签,带透明度
for area in [100, 300, 500]:
plt.scatter([], [], c='k', alpha=0.3, s=area,
label=str(area) + ' km$^2$')
plt.legend(scatterpoints=1, frameon=False, labelspacing=1, title='City Area')
plt.title('California Cities: Area and Population');
![](https://filescdn.proginn.com/e2a8b15179c6723c3dbe2aff2bcdeb56/8f427089df89c52f6bcea54135efe7ed.webp)
多重图例
fig, ax = plt.subplots()
lines = []
styles = ['-', '--', '-.', ':']
x = np.linspace(0, 10, 1000)
for i in range(4):
lines += ax.plot(x, np.sin(x - i * np.pi / 2),
styles[i], color='black')
ax.axis('equal')
# 指定第一个图例的线条和标签
ax.legend(lines[:2], ['line A', 'line B'],
loc='upper right', frameon=False)
# 手动创建第二个图例,并将作者添加到图表中
from matplotlib.legend import Legend
leg = Legend(ax, lines[2:], ['line C', 'line D'],
loc='lower right', frameon=False)
ax.add_artist(leg);
![](https://filescdn.proginn.com/154c43c703f85e0ef9ac5dced4e6530e/ee51af059a7ca777e2b5ca3956e1c0bd.webp)
7.个性化颜色条
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import numpy as np
x = np.linspace(0, 10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
plt.imshow(I)
plt.colorbar();
![](https://filescdn.proginn.com/ba4d871e7443d5998a9660321a8bec25/cb0a67cec59c43e4ad062049b2158bb3.webp)
自定义颜色条
plt.imshow(I, cmap='gray');
![](https://filescdn.proginn.com/29b7cd0f0fd781b8dbead544cf0a9d38/559a32728ed90a5d2e4b4987b75ce914.webp)
plt.cm.
选择色图
序列色图:这类型的色谱只包括一个连续序列的色系(例如binary或viridis)。 分化色图:这类型的色谱包括两种独立的色系,这两种颜色有着非常大的对比度(例如RdBu或PuOr)。 定性色图:这类型的色图混合了非特定连续序列的颜色(例如rainbow或jet)。
from matplotlib.colors import LinearSegmentedColormap
def grayscale_cmap(cmap):
"""返回给定色图的灰度版本"""
cmap = plt.cm.get_cmap(cmap) # 使用名称获取色图对象
colors = cmap(np.arange(cmap.N)) # 将色图对象转为RGBA矩阵,形状为N×4
# 将RGBA颜色转换为灰度
# 参考 http://alienryderflex.com/hsp.html
RGB_weight = [0.299, 0.587, 0.114] # RGB三色的权重值
luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight)) # RGB平方值和权重的点积开平方根
colors[:, :3] = luminance[:, np.newaxis] # 得到灰度值矩阵
# 返回相应的灰度值色图
return LinearSegmentedColormap.from_list(cmap.name + "_gray", colors, cmap.N)
def view_colormap(cmap):
"""将色图对应的灰度版本绘制出来"""
cmap = plt.cm.get_cmap(cmap)
colors = cmap(np.arange(cmap.N))
cmap = grayscale_cmap(cmap)
grayscale = cmap(np.arange(cmap.N))
fig, ax = plt.subplots(2, figsize=(6, 2),
subplot_kw=dict(xticks=[], yticks=[]))
ax[0].imshow([colors], extent=[0, 10, 0, 1])
ax[1].imshow([grayscale], extent=[0, 10, 0, 1])
view_colormap('jet')
![](https://filescdn.proginn.com/20fecb4f37f70b35490e591185953036/732f443cd991f8226bde1c8d87d74d26.webp)
view_colormap('viridis')
![](https://filescdn.proginn.com/b7119f08ed3117316af5f744a08ebdfc/ed6c5e4eb8864c4402557a74ab24e3ca.webp)
view_colormap('cubehelix')
![](https://filescdn.proginn.com/dcca76decb3791866b8a625611adc5e9/6284e87256c02ebfe263c3f139ad2add.webp)
view_colormap('RdBu')
![](https://filescdn.proginn.com/fa608064889ee6c18fb6c71c1055eb2f/7bec6cd3da2323d973baebe075a3a236.webp)
颜色限制和扩展
# 在I数组中人为生成不超过1%的噪声
speckles = (np.random.random(I.shape) < 0.01)
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles))
plt.figure(figsize=(10, 3.5))
# 不考虑去除噪声时的颜色分布
plt.subplot(1, 2, 1)
plt.imshow(I, cmap='RdBu')
plt.colorbar()
# 设置去除噪声时的颜色分布
plt.subplot(1, 2, 2)
plt.imshow(I, cmap='RdBu')
plt.colorbar(extend='both')
plt.clim(-1, 1);
![](https://filescdn.proginn.com/909fe4a8844e5688a916482ef9fb0678/9aac8ef3c1319c83fd4e188c3d5363b5.webp)
离散颜色条
plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1);
![](https://filescdn.proginn.com/e29d86dc36b7f39509d7531fcf5ff99d/9b8004abea92b261a8cd4bae13e6870b.webp)
例子:手写数字
# 读取数字0-5的手写图像,然后使用Matplotlib展示头64张缩略图
from sklearn.datasets import load_digits
digits = load_digits(n_class=6)
fig, ax = plt.subplots(8, 8, figsize=(6, 6))
for i, axi in enumerate(ax.flat):
axi.imshow(digits.images[i], cmap='binary')
axi.set(xticks=[], yticks=[])
![](https://filescdn.proginn.com/8a0649cef517e74f2f4b9c78fbe164bb/22a46292859560c2dc99234deb901f5c.webp)
# 使用Isomap将手写数字图像映射到二维流形学习中
from sklearn.manifold import Isomap
iso = Isomap(n_components=2)
projection = iso.fit_transform(digits.data)
# 绘制图表结果
plt.scatter(projection[:, 0], projection[:, 1], lw=0.1,
c=digits.target, cmap=plt.cm.get_cmap('cubehelix', 6))
plt.colorbar(ticks=range(6), label='digit value')
plt.clim(-0.5, 5.5)
![](https://filescdn.proginn.com/8f6296d2a5a1441cf2fd9f84b1b3f6cb/08721dc07bc80f9aaf7689dbdc83d5e6.webp)
8.多个子图表
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
plt.axes:手动构建子图表
ax1 = plt.axes() # 标准图表
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2]) #子图表
![](https://filescdn.proginn.com/795854ab08bb5d868aebb2fc5ccb78d7/fc8f8ee2244af75aa7037d5d8520c9f2.webp)
fig = plt.figure() # 获得figure对象
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],
xticklabels=[], ylim=(-1.2, 1.2)) # 左边10% 底部50% 宽80% 高40%
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],
ylim=(-1.2, 1.2)) # 左边10% 底部10% 宽80% 高40%
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x));
![](https://filescdn.proginn.com/45978438785958d84cd5c919ff4c4a16/ecdb4f514cb2a8ba2b4f0e74eff80235.webp)
plt.subplot:简单网格的子图表
for i in range(1, 7):
plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')
![](https://filescdn.proginn.com/9d50dcdc1defbe3ab0b5ede62999ad4f/429df7226e9af2d3fd26c78714d4e18c.webp)
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
ax = fig.add_subplot(2, 3, i)
ax.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')
![](https://filescdn.proginn.com/6a9d74501d9268e573ad80b907e98b53/cf5b554f52fca629fed6224050b80783.webp)
plt.subplots:一句代码设置所有网格子图表
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
![](https://filescdn.proginn.com/b8a0459807ebfc59c2e87ff8380c39e0/c7995232999bea2a2f7648986cf6ae06.webp)
# axes是一个2×3的数组,可以通过[row, col]进行索引访问
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)),
fontsize=18, ha='center')
fig
![](https://filescdn.proginn.com/5072d7da9fb17eded8fe2741c9d8cdae/ce7246863fbd663cd3b7d213a4ea881a.webp)
plt.GridSpec:更复杂的排列
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
plt.subplot(grid[0, 0])
plt.subplot(grid[0, 1:])
plt.subplot(grid[1, :2])
plt.subplot(grid[1, 2]);
![](https://filescdn.proginn.com/a6c73c3889e42eda4aaf19f8898cffcb/fedd754e4b650ae7dda35a5107232f78.webp)
# 构建二维正态分布数据
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T
# 使用GridSpec创建网格并加入子图表
fig = plt.figure(figsize=(6, 6))
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
# 在主图表中绘制散点图
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
# 分别在x轴和y轴方向绘制直方图
x_hist.hist(x, 40, histtype='stepfilled',
orientation='vertical', color='gray')
x_hist.invert_yaxis() # x轴方向(右下)直方图倒转y轴方向
y_hist.hist(y, 40, histtype='stepfilled',
orientation='horizontal', color='gray')
y_hist.invert_xaxis() # y轴方向(左上)直方图倒转x轴方向
![](https://filescdn.proginn.com/44ff4df424b2091db4079f96a38d70b5/90f5379c9005bd244b084be383bb80b5.webp)
9.文本和标注
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('seaborn-whitegrid')
import numpy as np
import pandas as pd
例子:节假日对美国出生率的影响
births = pd.read_csv(r'D:\python\Github学习材料\Python数据科学手册\data\births.csv')
quartiles = np.percentile(births['births'], [25, 50, 75])
mu, sig = quartiles[1], 0.74 * (quartiles[2] - quartiles[0])
births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)')
births['day'] = births['day'].astype(int)
births.index = pd.to_datetime(10000 * births.year +
100 * births.month +
births.day, format='%Y%m%d')
births_by_date = births.pivot_table('births',
[births.index.month, births.index.day])
births_by_date.index = [pd.datetime(2012, month, day)
for (month, day) in births_by_date.index]
C:\Users\gdc\Anaconda3\lib\site-packages\ipykernel_launcher.py:15: FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.
from ipykernel import kernelapp as app
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax);
![](https://filescdn.proginn.com/4f0c0af091184b3d39bee3db9f7b269b/afe7e0355505501200e92e00c38bfa57.webp)
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax)
# 在折线的特殊位置标注文字
style = dict(size=10, color='gray')
ax.text('2012-1-1', 3950, "New Year's Day", **style)
ax.text('2012-7-4', 4250, "Independence Day", ha='center', **style)
ax.text('2012-9-4', 4850, "Labor Day", ha='center', **style)
ax.text('2012-10-31', 4600, "Halloween", ha='right', **style)
ax.text('2012-11-25', 4450, "Thanksgiving", ha='center', **style)
ax.text('2012-12-25', 3850, "Christmas ", ha='right', **style)
# 设置标题和y轴标签
ax.set(title='USA births by day of year (1969-1988)',
ylabel='average daily births')
# 设置x轴标签月份居中
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%h'));
![](https://filescdn.proginn.com/016a09f03207197cc63ad47d956c1e4a/1930dc78bbcdc80a97aa863f77dd277a.webp)
转换和文本位置
ax.transData:与数据坐标相关的转换 ax.tranAxes:与 Axes 尺寸相关的转换(单位是 axes 的宽和高) ax.tranFigure:与 figure 尺寸相关的转换(单位是 figure 的宽和高)
fig, ax = plt.subplots(facecolor='lightgray')
ax.axis([0, 10, 0, 10])
# transform=ax.transData是默认的,这里写出来是为了明确对比
ax.text(1, 5, ". Data: (1, 5)", transform=ax.transData)
ax.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform=ax.transAxes)
ax.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform=fig.transFigure);
![](https://filescdn.proginn.com/895de886554c6ecc8e7e5286eef5f8d8/5811b96b67e05cebb02fbea7f4388026.webp)
ax.set_xlim(0, 2)
ax.set_ylim(-6, 6)
fig
![](https://filescdn.proginn.com/488c9d5cf6184990e018f5758f39d57f/e1ec89c881df64c50567eaca207a843f.webp)
箭头和标注
%matplotlib inline
fig, ax = plt.subplots()
x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')
ax.annotate('local maximum', xy=(6.28, 1), xytext=(10, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.annotate('local minimum', xy=(5 * np.pi, -1), xytext=(2, -6),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"));
![](https://filescdn.proginn.com/4d22eb7d5fb2a62650cb5c4106a8a64b/dcf548508202d9dbe1441231efe9b8c2.webp)
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax)
# 为图表添加标注
ax.annotate("New Year's Day", xy=('2012-1-1', 4100), xycoords='data',
xytext=(50, -30), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=-0.2"))
ax.annotate("Independence Day", xy=('2012-7-4', 4250), xycoords='data',
bbox=dict(boxstyle="round", fc="none", ec="gray"),
xytext=(10, -40), textcoords='offset points', ha='center',
arrowprops=dict(arrowstyle="->"))
ax.annotate('Labor Day', xy=('2012-9-4', 4850), xycoords='data', ha='center',
xytext=(0, -20), textcoords='offset points')
ax.annotate('', xy=('2012-9-1', 4850), xytext=('2012-9-7', 4850),
xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '|-|,widthA=0.2,widthB=0.2', })
ax.annotate('Halloween', xy=('2012-10-31', 4600), xycoords='data',
xytext=(-80, -40), textcoords='offset points',
arrowprops=dict(arrowstyle="fancy",
fc="0.6", ec="none",
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate('Thanksgiving', xy=('2012-11-25', 4500), xycoords='data',
xytext=(-120, -60), textcoords='offset points',
bbox=dict(boxstyle="round4,pad=.5", fc="0.9"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=80,rad=20"))
ax.annotate('Christmas', xy=('2012-12-25', 3850), xycoords='data',
xytext=(-30, 0), textcoords='offset points',
size=13, ha='right', va="center",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1));
# 设置图表标题和坐标轴标记
ax.set(title='USA births by day of year (1969-1988)',
ylabel='average daily births')
# 设置月份坐标居中显示
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%h'));
ax.set_ylim(3600, 5400);
![](https://filescdn.proginn.com/0cc363eebdd27398d9bba04354b9983e/164c4a9c49f678e6468c34cad7f4ba1a.webp)
10.自定义刻度
主要的和次要的刻度
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import numpy as np
ax = plt.axes(xscale='log', yscale='log', xlim=[10e-5, 10e5], ylim=[10e-5, 10e5])
ax.grid();
![](https://filescdn.proginn.com/bf07af9d1b01a1fddedd5034b44d74c3/b1078eaf2574ca1e2d3857a86315508a.webp)
print(ax.xaxis.get_major_locator())
print(ax.xaxis.get_minor_locator())
print(ax.xaxis.get_major_formatter())
print(ax.xaxis.get_minor_formatter())
隐藏刻度和标签
ax = plt.axes()
ax.plot(np.random.rand(50))
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())
![](https://filescdn.proginn.com/f58369620fed00ed8fba64a1b5e53f6d/3b14d023a7c2183869510a9a82b1a3b4.webp)
fig, ax = plt.subplots(5, 5, figsize=(5, 5))
fig.subplots_adjust(hspace=0, wspace=0)
# 从scikit-learn载入头像数据集
from sklearn.datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces().images
for i in range(5):
for j in range(5):
ax[i, j].xaxis.set_major_locator(plt.NullLocator())
ax[i, j].yaxis.set_major_locator(plt.NullLocator())
ax[i, j].imshow(faces[10 * i + j], cmap="bone")
downloading Olivetti faces from
https://ndownloader.figshare.com/files/5976027
to C:\Users\gdc\scikit_learn_data
![](https://filescdn.proginn.com/7c9ef38db93f5f239ac89f6dbb885abb/1f275234ea11ebe954308c31faddec3e.webp)
减少或增加刻度的数量
fig, ax = plt.subplots(4, 4, sharex=True, sharey=True)
![](https://filescdn.proginn.com/1301c492d3b2cb4d90bbc88c20bc4f2a/9e993088da8b43985074f7cb6ce5b889.webp)
# 对x和y轴设置刻度最大数量
for axi in ax.flat:
axi.xaxis.set_major_locator(plt.MaxNLocator(3))
axi.yaxis.set_major_locator(plt.MaxNLocator(3))
fig
![](https://filescdn.proginn.com/04a2df6e4a154180d5ec7fde1a312f5d/226d00539986201674c584172dba7ade.webp)
复杂的刻度格式
# 绘制正弦和余弦图表
fig, ax = plt.subplots()
x = np.linspace(0, 3 * np.pi, 1000)
ax.plot(x, np.sin(x), lw=3, label='Sine')
ax.plot(x, np.cos(x), lw=3, label='Cosine')
# 设置网格、图例和轴极限
ax.grid(True)
ax.legend(frameon=False)
ax.axis('equal')
ax.set_xlim(0, 3 * np.pi);
![](https://filescdn.proginn.com/b98820f4da593b3e3ced8e66e3525ca1/4f1f339f0b182e0aeda0d759f0213a6b.webp)
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 4))
fig
![](https://filescdn.proginn.com/f5315b13e72c156fc011bac594e6a014/ecc2a33050fa8b188e4eb663662d9c26.webp)
plt.FuncFormatter
,这个对象能够接受一个用户自定义的函数来提供对于刻度标签的精细控制:def format_func(value, tick_number):
# N是pi/2的倍数
N = int(np.round(2 * value / np.pi))
if N == 0:
return "0" # 0点
elif N == 1:
return r"$\frac{\pi}{2}$" # pi/2
elif N == 2:
return r"$\pi$" # pi
elif N % 2 > 0:
return r"$\frac{{%d}\pi}{2}$" %N # n*pi/2 n是奇数
else:
return r"${0}\pi$".format(N // 2) # n*pi n是整数
ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
fig
![](https://filescdn.proginn.com/8ad24b34f8e35f3a3f4776060884fe70/bc4bd96725e2be82ea4cda353823a7a8.webp)
Formatter 和 Locator 总结
NullLocator | |
FixedLocator | |
IndexLocator | |
LinearLocator | |
LogLocator | |
MultipleLocator | |
MaxNLocator | |
AutoLocator | |
AutoMinorLocator |
NullFormatter | |
IndexFormatter | |
FixedFormatter | |
FuncFormatter | |
FormatStrFormatter | |
ScalarFormatter | |
LogFormatter |
11.在 matplotlib 中创建三维图表
from mpl_toolkits import mplot3d
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
![](https://filescdn.proginn.com/69708b602a4f46ee77b39d81e4723e47/e9e18385e3b0b9cdce91e39c97f4533e.webp)
三维的点和线
ax = plt.axes(projection='3d')
# 三维螺旋线的数据
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'gray')
# 三维散点的数据
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');
![](https://filescdn.proginn.com/1a91f231d7abe9496d051fdc1b6271d0/cd5b9b96291d61f655d57e83bc15e30b.webp)
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
![](https://filescdn.proginn.com/dcc5d679417799aeee977cb3e1d09b5f/7cc952854fc5a8a00ef880e770093cd5.webp)
ax.view_init(60, 35)
fig
![](https://filescdn.proginn.com/b80978c4fe5b8558dbfe4753e071da83/87e96bd07616fd30d78c7a8cd6f5b8d5.webp)
框线图和表面图
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe');
![](https://filescdn.proginn.com/eb4b64d33c507b3ba19422ac1f639bbe/7ce3f1a35e6d01bb0f7ccfadcb0be5ed.webp)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_title('surface');
![](https://filescdn.proginn.com/d199798d200f01a6132c2d7be3cd9af0/cc79fd89a011bb771b5b0ddb875bbc1e.webp)
r = np.linspace(0, 6, 20)
theta = np.linspace(-0.9 * np.pi, 0.8 * np.pi, 40)
r, theta = np.meshgrid(r, theta)
X = r * np.sin(theta)
Y = r * np.cos(theta)
Z = f(X, Y)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap='viridis', edgecolor='none');
![](https://filescdn.proginn.com/85dcab600c4b342be2a4587dfc438887/086d70d41c73b60901f6bf3486be6c42.webp)
表面三角剖分
theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax = plt.axes(projection='3d')
ax.scatter(x, y, z, c=z, cmap='viridis', linewidth=0.5);
![](https://filescdn.proginn.com/1d2a97202fb373061d6f4a76a3efb140/7182115b570e65fc3ea1748696ef562c.webp)
ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, z,
cmap='viridis', edgecolor='none');
![](https://filescdn.proginn.com/9aafd8d47adaf490f3c5555157814c48/b7b205b1da48ea21da633bf7a8282402.webp)
例子:绘制莫比乌斯环
theta = np.linspace(0, 2 * np.pi, 30)
w = np.linspace(-0.25, 0.25, 8)
w, theta = np.meshgrid(w, theta)
phi = 0.5 * theta
# r是坐标点距离环形中心的距离值
r = 1 + w * np.cos(phi)
# 利用简单的三角函数知识算得x,y,z坐标值
x = np.ravel(r * np.cos(theta))
y = np.ravel(r * np.sin(theta))
z = np.ravel(w * np.sin(phi))
# 在底层参数的基础上进行三角剖分
from matplotlib.tri import Triangulation
tri = Triangulation(np.ravel(w), np.ravel(theta))
ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, z, triangles=tri.triangles,
cmap='viridis', linewidths=0.2);
ax.set_xlim(-1, 1); ax.set_ylim(-1, 1); ax.set_zlim(-1, 1);
![](https://filescdn.proginn.com/795b6942591c1f5d55e108a22222b340/df1bfe6181b96c62ffa1a486fd0e11df.webp)
参考资料
[1]PythonDataScienceHandbook:https://github.com/jakevdp/PythonDataScienceHandbook/tree/master/notebooks
首届珠港澳人工智能算法大赛即将开赛
赛题一:短袖短裤识别
赛题二:小摊贩占道识别
即将开赛 等你加入
![](https://filescdn.proginn.com/e72822071ebf3dad3154835419258d63/bfa902d986286e2305c2e9ebf5c5d0c4.webp)
评论