How to add text on surfaces of cubes. I'm trying to solve 3d packing problem but i have problem visualization because if there were 1000 cubes, how to identify each of them.So i need to write number on surfaces(every surfaces if it is possible).
output that i dont want:
output that i need:
Code:
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
import matplotlib.pyplot as plt
def cuboid_data2(o, size=(1,1,1)):
X = [[[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]],
[[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0]],
[[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
[[0, 0, 1], [0, 0, 0], [0, 1, 0], [0, 1, 1]],
[[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
[[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]]]
X = np.array(X).astype(float)
for i in range(3):
X[:,:,i] *= size[i]
X += np.array(o)
return X
def plotCubeAt2(positions,sizes=None,colors=None, **kwargs):
if not isinstance(colors,(list,np.ndarray)): colors=["C0"]*len(positions)
if not isinstance(sizes,(list,np.ndarray)): sizes=[(1,1,1)]*len(positions)
g = []
for p,s,c in zip(positions,sizes,colors):
g.append( cuboid_data2(p, size=s) )
return Poly3DCollection(np.concatenate(g),
facecolors=np.repeat(colors,6), **kwargs)
positions = [(-3,5,-2),(1,7,1)]
sizes = [(4,5,3), (3,3,7)]
colors = ["lightblue","pink"]
fig = plt.figure()
ax = fig.gca(projection='3d')
# ax.set_aspect('equal')
pc = plotCubeAt2(positions,sizes,colors=colors, edgecolor="k")
ax.add_collection3d(pc)
ax.set_xlim([-4,6])
ax.set_ylim([4,13])
ax.set_zlim([-3,9])
plt.show() ```
You can add text
to 3D-Axes specifying the position and direction. The following example puts the text on the center of the frontal xz face of each box:
xz_sizes = np.array(sizes)
xz_sizes[:,1] = 0
label_pos = (np.array(positions) + xz_sizes / 2).tolist()
labels = ['12', '24']
for pos, label in zip(label_pos, labels):
ax.text( *pos, label, 'x', ha='center', va='center')
PS: if you like you can directly calculate label_pos
as a one-liner but for me this seems to be more convoluted than using the auxiliary array xz_sizes
:
label_pos = (np.array(positions) + np.insert(np.array(sizes)[:, [0,2]], 1, 0, axis=1) / 2).tolist()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.