散点图与曲面图的组合

16 投票
3 回答
36497 浏览
提问于 2025-04-17 18:01

我该怎么把一个3D散点图和一个3D曲面图结合起来,同时让曲面图保持透明,这样我就能看到所有的点呢?

3 个回答

0

如果你想在三维图上面画点,可以使用 zorder。比如,下面这段代码会生成:

ax = plt.axes(projection='3d', elev=35, azim=-125)
ax.plot_surface(x, y, z, cmap=plt.cm.coolwarm, linewidth=0.1, zorder=1)
ax.plot(scatter_x, scatter_y, scatter_z, 'b.', markersize=10, label='top', zorder=4)

enter image description here

19

使用这个回答中的代码;与其通过cmap=theCM命令来设置透明度,不如直接调整alpha值更简单。

ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot, alpha=0.2)

在这里输入图片描述

20

下面的代码绘制了一个3D散点图和一个3D表面图:

import matplotlib.pyplot as plt
import numpy as np
from random import random, seed
from matplotlib import cm
import matplotlib as mpl

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')              # to work in 3d

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, ec='k')  # 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图形示例。

我把表面图的颜色从默认的改成了一个叫hot的颜色映射,这样可以更容易区分两个图的颜色——现在可以看到,表面图覆盖了散点图,这和绘制的顺序无关

要解决这个问题,可以在表面图的颜色映射中使用透明度;可以添加来自透明颜色映射的代码。

然后把这一行:

ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot)  # plot a 3d surface plot

改成:

theCM = mpl.colormaps.get_cmap('bwr')
theCM._init()
alphas = np.abs(np.linspace(-1.0, 1.0, theCM.N))
theCM._lut[:-3,-1] = alphas

# other code

ax.plot_surface(x_surf, y_surf, z_surf, cmap=theCM)

这里插入图片描述

撰写回答