Home > Net >  How to add text on surfaces of cubes
How to add text on surfaces of cubes

Time:08-13

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 dont want

output that i need:

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() ```

CodePudding user response:

You can add enter image description here

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()

Update: putting the labels on all surfaces works exactly the same way: the following examples show it for two other surfaces (1 x front, 1 x back), so I guess you get the idea:

label_pos_y = (np.array(positions)   np.insert(np.array(sizes)[:, [0,2]] / 2, 1, 0, axis=1)).tolist()
label_pos_x = (np.array(positions)   np.insert(np.array(sizes)[:, [1,2]] / 2, 0, 0, axis=1)).tolist()
label_pos_z = (np.array(positions)   np.insert(np.array(sizes)[:, [0,1]] / 2, 2, np.array(sizes)[:,2], axis=1)).tolist()

labels = ['12', '24']
for pos_y, pos_x, pos_z, label in zip(label_pos_y, label_pos_x, label_pos_z, labels):
    ax.text( *pos_y, label, 'x', ha='center', va='center')
    ax.text( *pos_x, label, 'y', ha='center', va='center')
    ax.text( *pos_z, label, 'x', ha='center', va='center')

enter image description here

  • Related