Plotting points as 3D spheres using Plotly

Viewed 134

I have data in the form of tables, which I wish to plot as 3D spheres - where the point would represent a sphere of radius r = value of the point.
Eg: point=4.7 --> sphere of radius 4.7

Example:

Table 1, would result in 15 spheres, at say height z=1:

1 2 3 4 5
4.5 4.9 4.9 4.9 4.7
4.5 4.8 4.8 4.8 4.8
4.3 4.7 4.7 4.9 4.9

Table 2, would result in another 15 spheres shifted "upward", at say height z=2:

1 2 3 4 5
4.3 4.7 4.7 4.9 4.7
4.4 4.8 4.8 4.8 4.7
4.5 4.9 4.9 4.9 4.8
1 Answers

I was eventually able to figure this out, the key idea was to use the marker parameter, which in-turn has a size property (ref: plotly documentation)

Example Code:

Convert the dataframes into list of numpy arrays, using the Pandas to_numpy() method and then flattening each array using the NumPy flatten() method.
For example: arrList.append(df.iloc[0:5,:].to_numpy().flatten()).
NOTE: My data also contains blanks in the form of "-".

arrList =
[array([2.5, 2.7, 3.9, 3.8, 3.9, 2.6, 2.5, 2.5, 3.9, 3.7, 2.4, 2.6, 2.4, 4,
        3.9, 2.5, 2.3, 2.3, 3.9, 3.7, 3.8, 3.9, 3.6, 3.7, 3.8, 3.7, 3.7,
        3.7, 3.8, 3.9], dtype=object),
 array([3.8, 3.9, 2.7, 3, 2.6, 3.9, 3.3, 2.9, 2.7, 3.8, 4, 3.6, 3.9, 3.8,
        3.9, 3.7, 3.8, 4, 3.9, 3.6, 3.8, 3.9, '-', '-', '-', 3.9, 3.9, '-',
        '-', '-'], dtype=object)]

Since the size property assigns a size in pixels, I have defined a method to "increase" the pixels by x-times (3x in my case), for float and/or int values in my data

def sizeMask(s):
    sphereSize = lambda s: s if isinstance(s, float) else s if isinstance(s, int) else 0.0
    vec_sphereSize = np.vectorize(sphereSize)
    return vec_sphereSize(s)
sizeList = [sizeMask(arr)*3.0 for arr in arrList]
sizeList =
[array([ 7.5,  8.1, 11.7, 11.4, 11.7,  7.8,  7.5,  7.5, 11.7, 11.1,  7.2,
         7.8,  7.2, 12. , 11.7,  7.5,  6.9,  6.9, 11.7, 11.1, 11.4, 11.7,
        10.8, 11.1, 11.4, 11.1, 11.1, 11.1, 11.4, 11.7]),
 array([11.4, 11.7,  8.1,  9. ,  7.8, 11.7,  9.9,  8.7,  8.1, 11.4, 12. ,
        10.8, 11.7, 11.4, 11.7, 11.1, 11.4, 12. , 11.7, 10.8, 11.4, 11.7,
         0. ,  0. ,  0. , 11.7, 11.7,  0. ,  0. ,  0. ])]

Finally, the plot is generated as follows:

x = np.asarray([[i]*5 for i in range(1,7)]).flatten()
y = np.asarray([np.arange(1,6)]*6).flatten()

data=[]
for i,arr in enumerate(arrList):
    data.append(go.Scatter3d(x=x, y=y,
                             z=np.asarray([i+1]*30),
                             mode='markers',
                             marker=dict(size=sizeList[i], showscale=False)))
    
fig = go.Figure(data=data)
fig.show()

Plotting points as 3D spheres using Plotly

Related