简体   繁体   中英

3D Scatter Plot in Plotly using DataFrame

I would like to generate a 3D Scatter chart using plotly. I've tried two different methods for creating the chart. Netither one has been successful. The first code does not do anything. This was the method that plotly usings in their reference. There is not a traceback error. No chart is shown or generated.

import plotly.plotly as py
import plotly.graph_objs as go
import cufflinks as cf
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot
plotly.offline.init_notebook_mode()
init_notebook_mode()
cf.go_offline()

df.iplot(kind='scatter', mode='markers', x='x', y='y', z='label')

This next code provides a "NameError: name 'z' is not defined". Are there any tricks or tips to creating a 3D scatter from a dataframe?

import plotly.plotly as py
import plotly.graph_objs as go
import cufflinks as cf
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot
plotly.offline.init_notebook_mode()
init_notebook_mode()
cf.go_offline()

trace1 = go.Scatter3d(
    x=df['x'],
    y=df['y'],
    z=df['label'],
    mode='markers',
    marker=dict(
        size=12,
        color=z,                # set color to an array/list of desired values
        colorscale='Viridis',   # choose a colorscale
        opacity=0.8
    )
)



data = [trace1]
layout = go.Layout(
    margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    )
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='DF')

Trace Back:

File "", line 8, in color=z, # set color to an array/list of desired values

NameError: name 'z' is not defined

The dataframe was generated using the following code:

dist = 1 - cosine_similarity(vcx)
MDS()
mds = MDS(n_components=k, dissimilarity="precomputed", random_state=1)
pos = mds.fit_transform(dist)  # shape (n_components, n_samples)
xs, ys = pos[:, 0], pos[:, 1]
df = pd.DataFrame(dict(x=xs, y=ys, label=clusters, title=titles)) 

I have been able to generate a 3D scatter using the dataframe in pyplot but not in plotly.

Quite old question, but for anyone who want the answer : Instead of (line 17):

        color=z,                         # set color to an array/list of desired values

You should put :

        color=df['label'],                # set color to an array/list of desired values

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