前面学了几类简单的图形绘制,pie、hist、scatter、plot和stackplot,接下来继续学一些有趣的绘图。
一、绘制子图
绘制子图时,我们实验 pyplot.subplot
,函数定义如下:
matplotlib.pyplot.subplot(*args, **kwargs)
调用格式:subplot(nrows, ncols, index, **kwargs)
举个例子:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0, 2*np.pi, 50)
y1 = np.cos(np.pi * x)
y2 = np.sin(np.pi * x)
y3 = np.exp(x)
y4 = np.cos(2 * np.pi * x) * np.exp(-x)
plt.subplot(2, 2, 1)
plt.plot(x, y1, '.-', color="#ffaaaa")
plt.title('A tale of 2 subplots')
plt.ylabel('y1')
plt.subplot(2, 2, 2, projection="polar")
plt.plot(x, y2, '.-', color="#aaffcc")
plt.xlabel('time (s)')
plt.ylabel('y2')
plt.subplot(2, 2, 3)
plt.plot(x, y3, '.-', color="#aaaaff")
plt.xlabel('time (s)')
plt.ylabel('y3')
plt.subplot(2, 2, 4)
plt.plot(x, y4, '.-', color="orange")
plt.xlabel('time (s)')
plt.ylabel('y4')
plt.show()
其中,projection="polar"
表示将结果映射到极坐标
此外,还可以实使用其他排版,比如:
import numpy as np
import matplotlib.pyplot as plt
# 直方图
plt.subplot(2, 1, 1)
population_age = [22,55,62,45,21,22,34,42,42,4,99,102,110,
120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
bins = [10*i for i in range(14)]
plt.hist(population_age, bins,bottom=0, density=True, histtype="bar", align="mid",
rwidth=0.8, log=True, orientation="vertical", color="lightblue", label="bar")
plt.legend()
# 饼图
plt.subplot(2, 2, 3)
factors = [15, 30, 45, 10]
labels = ["young", "Hogs", "Dogs", "Logs"]
kwargs = dict(labels=labels,startangle=90, radius=1.2,
shadow=True,explode=(0,0.1,0,0),autopct="%1.1f%%")
plt.pie(factors, **kwargs)
plt.title("Pie")
# 绘制散点图
plt.subplot(2, 2, 4)
x = [1,2,3,4,5,6,7,8,9]
y = [5,2,4,2,1,4,5,2,3]
plt.scatter(x, y, label="skitscat", color="#ffaaaa",
s=40, marker="*", alpha=1.0, linewidth=0.1, edgecolor="r")
plt.show()
这里需要注意图的 index
, 不同 rows*cols
的排版可以随意搭配,但是需要知道图的位置,图的位置由(rows, cols, index)唯一确定:
绘制结果:
二、绘制3D图形
首先,看一个简单的3D曲线:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 定义图象和空间坐标系
fig = plt.figure()
ax = Axes3D(fig)
# 螺旋线 r=5
z = np.linspace(0, 6*np.pi, 1000)
x = 5 * np.sin(z)
y = 5 * np.cos(z)
# 描点
zd = np.linspace(0, 6*np.pi, 100)
xd = 5 * np.sin(zd)
yd = 5 * np.cos(zd)
#绘制3D图
ax.scatter3D(xd, yd, zd, color="#aaaaff", marker='*')
ax.plot3D(x, y, z, 'gray', color="#aacccc")
plt.show()
step1: 定义图象和空间坐标系
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
step2:设置x, y, z坐标
# 螺旋线 r=5
z = np.linspace(0, 6*np.pi, 1000)
x = 5 * np.sin(z)
y = 5 * np.cos(z)
绘制结果如下:
下面,继续绘制3D曲面:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection='3d')
xx = np.arange(-2*np.pi, 2*np.pi, 0.1)
yy = np.arange(-2*np.pi, 2*np.pi, 0.1)
X, Y = np.meshgrid(xx, yy)
Z = np.sin(X)*np.sin(Y)
ax.plot_surface(X, Y, Z, cmap="rainbow") # cmap为颜色映射,可以取"winter", "rainbow"等
plt.show()
说明:
(1)ax = plt.axes(projection='3d')
与前面的 ax = Axes3D(fig)
,都是创建空间坐标系
(2)X, Y = mashgrid(x, y)函数:将x,y简单的复制为len(x)*len(y)的数组,其中X为x按行复制len(y)次,Y为y按列复制len(x)次。
import numpy as np
x = [1, 2, 3]
y = [4, 5, 6, 7]
X, Y = np.meshgrid(x, y)
print("X = \n", X)
print("Y = \n", Y)
得到结果如下:
X =
[[1 2 3]
[1 2 3]
[1 2 3]
[1 2 3]]
Y =
[[4 4 4]
[5 5 5]
[6 6 6]
[7 7 7]]
***Repl Closed***
绘制结果如下:
接着,我们优化上面的3D图,设置步长(line 15),加上等高线(line 18)
# 3D曲面
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection='3d')
xx = np.arange(-2*np.pi, 2*np.pi, 0.1)
yy = np.arange(-2*np.pi, 2*np.pi, 0.1)
X, Y = np.meshgrid(xx, yy)
Z = np.sin(X)*np.sin(Y)
# cstride=1 => 行列方向步长相同
ax.plot_surface(X, Y, Z, cstride=1, cmap="rainbow")
# 生成z方向的投影,投到 x-y 平面
ax.contour(X, Y, Z, zdir='z', offset=-1, cmap="rainbow")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()
效果展示:
参考内容:使用matplotlib绘制3D图形