结合散点图和表面图
如何将3D散点图与3D表面图结合起来,同时保持表面图透明,以便仍然可以看到所有点?
-
要在同一张图中组合各种类型的图,您应该使用函数
plt.hold(True)。
以下代码绘制了带有3D表面图的3D散点图:
from mpl_toolkits.mplot3d import * import matplotlib.pyplot as plt import numpy as np from random import random, seed from matplotlib import cm fig = plt.figure() ax = fig.gca(projection='3d') # to work in 3d plt.hold(True) x_surf=np.arange(0, 1, 0.01) # generate a mesh y_surf=np.arange(0, 1, 0.01) x_surf, y_surf = np.meshgrid(x_surf, y_surf) z_surf = np.sqrt(x_surf+y_surf) # ex. function, which depends on x and y ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot); # plot a 3d surface plot n = 100 seed(0) # seed let us to have a reproducible set of random numbers x=[random() for i in range(n)] # generate n random points y=[random() for i in range(n)] z=[random() for i in range(n)] ax.scatter(x, y, z); # plot a 3d scatter plot ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_zlabel('z label') plt.show()
结果:
- 您可以在此处看到其他一些带有3d图的示例:http
- //matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
为了将两个图的颜色区分开,我将表面图的颜色从默认值更改为“热”色图- 现在,可以看出表面图覆盖了散点图,而与顺序无关…
编辑: 要解决该问题,应在表面图的颜色图中使用透明度;在以下位置添加代码:透明的颜色图 并更改线:
ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot); # plot a 3d surface plot
至
ax.plot_surface(x_surf, y_surf, z_surf, cmap=theCM);