简体   繁体   中英

Setting markers colour in plotly 3D scatterplot according to R, G, B stored in DataFrame columns

I have the following pandas DataFrame:

>>> print(df.head())
         X         Y        Z   R   G   B
0 -846.160 -1983.148  243.229  22  24  19
1 -846.161 -1983.148  243.229  31  37  28
2 -846.157 -1983.148  243.231  20  21  18
3 -846.160 -1983.148  243.230  21  25  18
4 -846.159 -1983.147  243.233  38  48  34

And I plot data from it to 3D scatter plot like this:

import plotly.express as px
fig = px.scatter_3d(df, x='X', y='Y', z='Z')
fig.update_traces(marker=dict(size=4), selector=dict(mode='markers'))
fig.show()

The plot looks like below.

在此处输入图片说明

As you can see, every marker in the plot is blue. Is there any option, how to use my R , G , B columns from df DataFrame to change a colour of every marker in plot?

You can use graph_objs.Scatter3d :

import pandas as pd
import plotly.graph_objs as go

df = pd.DataFrame({'X': [1,2,3,4,5,],
                   'Y': [1,3,2,4,1],
                   'Z': [4,1,3,4,1],
                   'R': [252, 11, 250, 21, 8],
                   'G': [1, 127, 251, 25, 244],
                   'B': [1, 28, 8, 128, 4]})

trace = go.Scatter3d(x=df.X,
                      y=df.Y,
                      z=df.Z,
                      mode='markers',
                      marker=dict(size=5,
                                  color=['rgb({},{},{})'.format(r,g,b) for r,g,b in zip(df.R.values, df.G.values, df.B.values)],
                                  opacity=0.9,))

data = [trace]

layout = go.Layout(margin=dict(l=0,
                               r=0,
                               b=0,
                               t=0))

fig = go.Figure(data=data, layout=layout)
fig.show()

and you get:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM