kirti purohit
kirti purohit

Reputation: 431

Plotly 3D plot in python

I want to make 3D plot in python using plotly. Actually its the first step of an animation but first I need to know how to create a 3D scatter plot of it as shown below which is made in matplotlib. I have the dataset which looks like this.

enter image description here

Now, I want to animate it against the dates mentioned but the code I am getting on official site of plotly like this and most of them are similar.

import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
              color='species')
fig.show()

Now, I'm not able to understand how should I assign X,Y and Z to get an animated plot. Because all the 13 columns I need in the plot against the date.

enter image description here

For reference I found this site Which said,

To get a 3D scatter plot you need to specify the trace as a plotly.graph_objs.Scatter3d object or as a dict with a type: 'scatter3d' key.

Feel free to share a full reproducible example if you’d like to work through more of the details.

But this wasn't enough.

Please help me with this. A link of proper code or guidance would be really helpful to how set variables to get a 3D plot animation. Thank you.

Upvotes: 0

Views: 2251

Answers (1)

William
William

Reputation: 421

For updating existing plots in plotly, they have the FigureWidget interface. If you can operate in an environment where the widgets work (e.g. Jupyter notebook), then the following code will repeatedly update the data in an existing plot.

It doesn't look great as an animation. And if the data updates while you are rotating the view, it jerks back to the original position. So that's not great. But if you are okay with those limitations, this will get you started.

import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
              color='species')

import threading
import time
import numpy as np
fw = go.FigureWidget(fig)

def do():
    while True:
        fw.data[0]['x'] = np.random.rand(len(fw.data[0]['x']))
        time.sleep(1)

t = threading.Thread(target=do)
t.start()

fw # run this in cell after which the plot will be generated.

This is how it looks. Note the unfortunate jumpiness during rotating the view. enter image description here

Upvotes: 2

Related Questions