运行环境:window10+python 3.7.7
Matplotlib是一个优秀的2D和3D图形库,用于生成科学图形。以下是它的优势:
很容易开始使用
支持LaTeX
配置图表所有元素的好机会。
高质量输出各种格式的图像(PNG、PDF、SVG、EPS、PGF)。
图形界面,支持无界面图形生成。
目录
1.# 这一行允许matplotlib在jupyter笔记本中显示图形。而不是为每个图表打开一个新窗口。
1.# 这一行允许matplotlib在jupyter笔记本中显示图形。而不是为每个图表打开一个新窗口。
%matplotlib inline
2.所用相关库:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
3.一个类似MATLAB绘图API的简单图。
#构建所画图的函数公式并简单画图
x=np.linspace(0,50)
y = np.linspace(0,150)
plt.figure()
plt.plot(x, y, 'r',color='blue')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('The graph with a straightness. ')
plt.show()
#示例2-设置多张图片在一张画布上
plt.subplot(1,2,1) # subplot(nrows, ncols, index, **kwargs)
#将画布分为1行2列,现在画第一张图
# index starts at 1 in the upper left corner and increases to the right
plt.plot(x, y, 'r--')
plt.subplot(1,2,2)
#将画布分为1行2列,现在画第二张图
plt.plot(y, x, 'g*-');
#示例3-设置画布的大小
fig = plt.figure()
axes = fig.add_axes([0.2, 0.1, 0.8, 0.8])
# dimensions of the new axes: left, bottom, width, height (range 0 to 1)
#四个指数对应:左,底,宽,高,范围需在0-1之间
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
#示例4-在同一张画中,画小图
#注意:插入图会在主图上面,请看示例效果
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes主图尺寸
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes插入图尺寸
# main figure主图
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# insert插入的小图
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
#示例4-1 我们可以只将主图画出
fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
#示例4-2 将主图画出多个,可自行添加变量属性
fig, axes = plt.subplots(nrows=1, ncols=2)
for ax in axes:
ax.plot(x, y, 'r')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
4.图形尺寸、纵横比和DPI
Matplotlib允许你在使用figsize和dpi参数创建Figure对象时,设置图表的纵横比、DPI和尺寸。figsize-图表的宽度和高度,单位为英寸,dpi--每英寸的像素(点)数。要创建一个800x400像素,100DPI的图像,我们可以执行:
fig = plt.figure(figsize=(8,4), dpi=100)
同样的参数可以转移到其他对象,例如函数 subplots
fig, axes = plt.subplots(figsize=(12,3))
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
5.保存图表
要保存图表,可以使用fig.savefig
fig.savefig("filename.png")
你还可以选择DPI和输出文件格式:
fig.savefig("filename.png", dpi=200)
可选格式:Matplotlib可以生成各种格式的图像,如PNG、JPG、EPS、SVG、PGF和PDF。对于学术文章,建议使用PDF格式。在某些情况下,PGF格式可能是一个不错的选择。
图解、坐标轴名称和图表名称
#图解
ax.legend(["curve1", "curve2", "curve3"]);#针对图中每条线的图解说明
#坐标轴名称
ax.set_xlabel("x")
ax.set_ylabel("y");
#图表名称
ax.set_title("title");
需要注意的,以上的图解方法容易出错,如果在图表中添加或删除曲线,会显得不灵活。比较合适的方法是当曲线或其他对象添加到图形中时,使用llabel="label text"参数,然后使用legend参数的图解方法添加图解。这种方法的优点是,如果图表中增加或删除图表,图例会自动更新。legend函数也接受参数loc,它可以用来指示图例在图表中的位置。
ax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();
ax.legend(loc=0) # let matplotlib decide the optimal location
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
# .. many more options are available
上述方法的使用实例。
fig, ax = plt.subplots()
ax.plot(x, label="y = x")
ax.plot(x, label="y = x")
ax.legend(loc=2); # upper left corner
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title');
6.设置颜色、线条粗细、线条类型
6.1颜色
ax.plot(x, x**2, 'b.-') # 蓝色虚线
ax.plot(x, x**3, 'g--') # 绿色条状线条
也可以使用RGB十六进制代码和颜色参数设置颜色,并设置透明度。
fig, ax = plt.subplots()
ax.plot(x, x+1, color="red", alpha=0.5) # 红线
ax.plot(x, x+2, color="#1155dd") # RGB 蓝色代码
ax.plot(x, x+3, color="#15cc55") # RGB 绿色代码
6.2线条粗细
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)
# possible linestype options ‘-‘, ‘--’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')
# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...
# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="green", lw=2, ls='--', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='--', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='--', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='--', marker='1')
# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,
markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");
6.3线条设置
6.3.1构建范围
构建范围的调整可以使用以下方法进行set_ylim
和set_xlim
, 以及 axis('tight')
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")
axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")
axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");
6.3.2对数的取值
fig, axes = plt.subplots(1, 2, figsize=(10,4))
axes[0].plot(x, x**2, x, np.exp(x))
axes[0].set_title("Normal scale")
axes[1].plot(x, x**2, x, np.exp(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)");
6.3.3添加网格
fig, axes = plt.subplots(1, 2, figsize=(10,3))
# сетка по умолчанию
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)
# 定制网格
axes[1].plot(x, x**2, x, x**3, lw=2)
axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)
6.3.4添加副轴
fig, ax1 = plt.subplots()
ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx() # create a twin axes
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
label.set_color("red")
7.其他的2D图形
n = np.array([0,1,2,3,4,5])
fig, axes = plt.subplots(1, 4, figsize=(12,3))
xx = np.linspace(-0.75, 1., 100)
axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")
axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5) # categorical data
axes[2].set_title("bar")
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between");
# 极坐标
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = np.linspace(0, 2 * np.pi, 100)
ax.plot(t, t, color='blue', lw=3);
# 直方图
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize=(12,4))
axes[0].hist(n)
axes[0].set_title("Default histogram")
axes[0].set_xlim((min(n), max(n)))
axes[1].hist(n, cumulative=True, bins=50)
axes[1].set_title("Cumulative detailed histogram")
axes[1].set_xlim((min(n), max(n)));
8.文本摘要
可以使用以下方法进行注释text
fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3)
ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue")
ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green");
9.在一个窗口中显示多个图表
9.1subplots
fig, ax = plt.subplots(2, 3)
fig.tight_layout()
9.2subplot2grid
fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3) # number of columns for the axis to span downwards
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2) # number of columns for the axis to span downwards
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2) # number of rows for the axis to span to the right
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
fig.tight_layout()
9.3gridspec
import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
ax = fig.add_subplot(g)
fig.tight_layout()
9.4add_axes
使用add_axes手动添加轴,对于在图形中添加副图很有用。
fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3)
fig.tight_layout()
# inset
inset_ax = fig.add_axes([0.2, 0.55, 0.35, 0.35]) # X, Y, width, height
inset_ax.plot(xx, xx**2, xx, xx**3)
inset_ax.set_title('zoom near origin')
# set axis range
inset_ax.set_xlim(-.2, .2)
inset_ax.set_ylim(-.005, .01)
# set axis tick locations
inset_ax.set_yticks([0, 0.005, 0.01])
inset_ax.set_xticks([-0.1,0,.1]);
10.彩图和等高线图形
#所用数据
alpha = 0.7
phi_ext = 2 * np.pi * 0.5
def flux_qubit_potential(phi_m, phi_p): # потенциал потока
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
10.1pcolor
fig, ax = plt.subplots()
p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max()) # vmin, vmax - colorbar range
cb = fig.colorbar(p, ax=ax)
10.2imshow
fig, ax = plt.subplots()
im = ax.imshow(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')
cb = fig.colorbar(im, ax=ax)
10.3contour
fig, ax = plt.subplots()
cnt = ax.contour(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
11.3D图
要使用3D图形,您必须首先导入类对象Axes3D。
from mpl_toolkits.mplot3d.axes3d import Axes3D
11.1地貌图
fig = plt.figure(figsize=(14,6))
# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)
# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
11.2框架图
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
11.3等高线图形
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=matplotlib.cm.coolwarm)
ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi);
11.4变换视角
可以使用view_init方法改变视角,该方法接受两个参数:elevation
和 azimuth
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1,2,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(30, 45)
ax = fig.add_subplot(1,2,2, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
ax.view_init(70, 30)
fig.tight_layout()