除了绘制经典的二维图表外,matplotlib还支持绘制三维图表,通过mplot3d工具可以实现,只需要在axes对象中指定projection参数为3d即可,常见的折线图,散点图,柱状图,等高线图等都可以进行三维图表的绘制,只需要同时提供x,y,z三个坐标轴对应的值即可,下面来看下具体用法
1. 折线图
示例如下
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = plt.axes(projection='3d')
>>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
>>> z = np.linspace(-2, 2, 100)
>>> r = z ** 2 + 1
>>> x = r * np.sin(theta)
>>> y = r * np.cos(theta)
>>> ax.plot(x, y, z)
[<mpl_toolkits.mplot3d.art3d.Line3D object at 0x095412C8>]
>>> plt.show()
输出结果如下
2. 散点图
示例如下
>>> fig = plt.figure()
>>> ax = plt.axes(projection='3d')
>>> for mark,start, end in (['o', 10, 20], ['^', 5, 30]):
... xs = np.random.choice(np.arange(23, 32), 50)
... ys = np.random.choice(np.arange(0, 100), 50)
... zs = np.random.choice(np.arange(start, end), 50)
... ax.scatter(xs, ys, zs, marker=mark)
...
>>> plt.show()
输出结果如下
3. 柱状图
示例如下
>>> fig = plt.figure()
>>> ax = plt.axes(projection='3d')
>>> yticks = [3, 2, 1]
>>> for i in yticks:
... x = np.arange(10)
... y = np.random.rand(10)
... ax.bar(x, y, zs=i, zdir='y')
...
<BarContainer object of 10 artists>
<BarContainer object of 10 artists>
<BarContainer object of 10 artists>
>>> plt.show()
输出结果如下
4. 热图
示例如下
>>> fig = plt.figure()
>>> ax = plt.axes(projection='3d')
>>> X = np.arange(-5, 5, 0.25)
>>> Y = np.arange(-5, 5, 0.25)
>>> X, Y = np.meshgrid(X, Y)
>>> R = np.sqrt(X ** 2 + Y ** 2)
>>> Z = np.sin(R)
>>> ax.plot_surface(X, Y, Z, cmap = 'RdBu')
<mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x00A66D48>
>>> plt.show()
输出结果如下
除了以上基本类型外,matplotlib还支持更多的3D图表类型,具体用法请查看官方文档。
·end·