简体   繁体   中英

How to create 3d scatter plots for clustering in plotly with having each point color set to color of our choice?

I am working on a dataset clustering denoted by prediction 0 and 1 in k-means. I am now looking to plot the points for better visualizing them. I have converted my dataframe into 3d too.

import plotly
import plotly.graph_objects as go
import numpy as np
plotly.offline.init_notebook_mode(connected=True)
%matplotlib inline

colors = ["red", "gray"]

for i in range(len(x_pca)):
    fig = go.Figure(data=[go.Scatter3d(x=x,y=y,z=z, mode='markers',marker= 
    dict(size=12,color=colors[p[i]],opacity=0.8))])

fig.show()

### p is a list containing values in the form of 0,1,0,0,1.......
# x,y,z are all list containing the points convereted into 3d using pca.

With above code, I am able to print 3d plot but all points are having color as red.

I am looking to make points of two types into red and gray. Is there any way to do that?

df3 dataframe is made by using x,y,z and p list.

import plotly.graph_objects as go


import plotly.graph_objects as go

PLOT = go.Figure()

for C in list(df3d.p.unique()):

    PLOT.add_trace(go.Scatter3d(x = df3d[df3d.p == C]['x'],
                            y = df3d[df3d.p == C]['y'],
                            z = df3d[df3d.p == C]['z'],
                            mode = 'markers', marker_size = 8, marker_line_width = 1,
                            name = 'Cluster ' + str(C)))

You can create function for discrate colors. For example lets say we have data set below (xyzd):

2    2    2    0
3    3    3    1
4    4    4    1 
2    2    2    0

my_data = np.genfromtxt('data.txt', delimiter = '\t')

def Data_Color(i):

if (i >0):
    return "red"

elif (i <= 0):
    return "gray"

fig=go.Figure(go.Scatter3d(x=my_data[:,0],y=my_data[:,1],z=my_data[:,2],
                           showlegend=True,
                           mode='markers',
                           marker=dict(symbol='circle',
                                       size=10,
                                       color=list(map(Data_Color, my_data[:,3]))
                                       )
                           )
               )
fig.show()

Example Output

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