如何在三维表面上添加文本

2 投票
2 回答
1296 浏览
提问于 2025-04-18 07:19

我用 plot_surface 创建了一个底面是平行四边形的长方体。现在我想在其中一个表面上添加一些文字。我试过用 ax.text(3, 0.5, 1, "red", (1, 1, 0), color='red'),但是文字在表面上看不见。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(projection='3d')

# Face 1
x1 = np.array([[0, 5, 5, 0, 0],
               [0, 0, 0, 0, 0]])
y1 = np.array([[0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0]])
z1 = np.array([[0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0]])
# Face 2
x2 = np.array([[1, 1, 1, 0, 0],
               [0, 0, 0, 0, 0]])
y2 = np.array([[1, 1, 1, 0, 0],
               [0, 0, 0, 0, 0]])
z2 = np.array([[0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0]])
# Face 3
x3 = np.array([[0, 5, 6, 1, 0],
               [0, 0, 0, 0, 0]])
y3 = np.array([[0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0]])
z3 = np.array([[1, 1, 1, 1, 1],
               [1, 1, 1, 1, 1]])
# Face 4
x4 = np.array([[1, 6, 6, 1, 1],
               [1, 1, 1, 1, 1]])
y4 = np.array([[1, 1, 1, 1, 1],
               [1, 1, 1, 1, 1]])
z4 = np.array([[0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0]])
# Face 5
x5 = np.array([[0, 1, 6, 5, 0],
               [0, 0, 0, 0, 0]])
y5 = np.array([[0, 1, 1, 0, 0],
               [0, 0, 0, 0, 0]])
z5 = np.array([[0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0]])
# Face 6
x6 = np.array([[5, 6, 6, 5, 5],
               [1, 1, 1, 1, 0]])
y6 = np.array([[0, 1, 1, 0, 0],
               [0, 0, 0, 0, 0]])
z6 = np.array([[0, 0, 1, 1, 0],
               [0, 0, 0, 0, 0]])


ax.plot_surface(x1,y1,z1)
ax.plot_surface(x2,y2,z2)
ax.plot_surface(x3,y3,z3)
ax.plot_surface(x4,y4,z4)
ax.plot_surface(x5,y5,z5)
ax.plot_surface(x6,y6,z6)

ax.text(3, 0.5, 1, "red", (1, 1, 0), color='red')

plt.show()

该怎么做呢?

在这里输入图片描述

2 个回答

2

你可以使用 zorder:

ax.text(3, 0.5, 1, "red", (1, 1, 0), color='red', zorder=10)

这和不同元素的相对深度有关(跟 z 轴没有关系)

在这里输入图片描述

1

你的表面是完全不透明的。如果你给所有的表面加上透明度,就能看到文字了。试试在你的代码里加上 ax.plot_surface(x,y,z, alpha=0.5),这样就能看到效果了。

在这里输入图片描述

撰写回答