Unable to color points by their respective rgb values

I have a Pandas DataFrame pt_data of the xyz coordinates and rgb values of multiple points. I want to create a 3D scatter plot with each point colored by its rgb value.

I followed this post to use f-strings to define colors of the point markers.

x_data=pt_data['x']
y_data=pt_data['y']
z_data=pt_data['z']

fig2 = go.Figure(
    data = [go.Scatter3d(
        x=x_data,
        y=y_data,
        z=z_data,

        mode='markers',

        marker=dict(
            color=[f'rgb({pt_data['r'].iloc[i]}, {pt_data['g'].iloc[i]}, {pt_data['b'].iloc[i]})' for i in range(len(pt_data))],
            # color=[f'rgb({np.random.randint(0,256)}, {np.random.randint(0,256)}, {np.random.randint(0,256)})' for i in range(len(pt_data))],
            size=1,
            opacity=1.0,
        )
    )],
)

fig2.update_layout(
    height=1300,
    scene=dict(aspectmode='data'),
    template="plotly_dark",
)

fig2.update_scenes(camera_projection_type='orthographic')

# fig2.show()
fig2.write_html("./fig2.html")

However I got the following errors: **SyntaxError** **:** invalid syntax for the line where color is defined. Strangely, applying random rgb color as suggested in the reference post works fine.

May I ask what I have missed here to define rgb colors for the points?

Hey @oat ,

Like the error suggests this doesn’t have to do with Plotly but rather just Python syntax error.

The issue is that you are using single quotations for the f-string AND for elements in the formatted values.

It should work if you change it to:

color=[f"rgb({pt_data['r'].iloc[i]}, {pt_data['g'].iloc[i]}, {pt_data['b'].iloc[i]})" for i in range(len(pt_data))]

Also I would advise to do this as follows:

# Taking advantage of the fact that the string representation of a tuple is "(a, b, c)"
color=[f"rgb{tuple(pt_rgb)}" for pt_rgb in pt_data[["r", "g", "b"]].values]
1 Like

Thank you very much, @RenaudLN, for pointing out my Python syntax mistake and suggesting a far more succinct code.