How to create a 3D scatter plot with plotly with all markers individually colored?

146 views Asked by At

Following the suggestion HERE I have tried the following code to create a Scatter3D plot with plotly in a jupyter notebook so each marker is colored individually, like you can do with matplotlib and something like

plt.scatter(x,y, c=z)

Here is the code:

cmap = matplotlib.colormaps['brg']
param = "elevation_deg"
min_value = min(vector)
max_value = max(vector)
range_ = max_value - min_value
colors = []
for value in vector:
    rgba = cmap((value-min_value)/range_)
    colors.append(f"rgb({int(255*rgba[0])},{int(255*rgba[1])},{int(255*rgba[2])})")
        
# Configure the trace.
trace = go.Scatter3d(
    x=x, 
    y=y,  
    z=z, 
    mode='markers',
    marker=dict(colors, size=10)
)

But I get the error

ValueError: dictionary update sequence element #0 has length 13; 2 is required

I also had a look at the documentation for Scatter3D, but I am totally lost in this page, it is totally confusing.

So maybe there is a more way way to do so? And also how to plot the colorbar, as you can do with matplotlib with plt.colorbar()?

1

There are 1 answers

2
Mahboob Nur On BEST ANSWER

Try this one. It is working for me.

import plotly.graph_objects as go
import numpy as np

# Generate some sample data
np.random.seed(50)
n = 5
x = np.random.rand(n)
y = np.random.rand(n)
z = np.random.rand(n)
color_values = np.random.rand(n)  

fig = go.Figure()

scatter = fig.add_trace(go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(
        color=color_values,  # Assigning the color values
        colorscale='Viridis',  # Choosing a color scale
        colorbar=dict(title='Colorbar Title'),  # Adding a color bar with title
        size=5
    )
))

fig.update_layout(
    scene=dict(
        xaxis=dict(title='X Axis', range=[0.2, 0.6]),  
        yaxis=dict(title='Y Axis', range=[0.4, 0.8]), 
        zaxis=dict(title='Z Axis', range=[0.1, 0.5])  
    )
)

fig.show()

Plot Image