Home > Blockchain >  How to plot 3D surface plots using Plotly in Python?
How to plot 3D surface plots using Plotly in Python?

Time:04-14

I am able to get a Surface Plot using matplotlib with this code:

ax = figure.gca(projection = "3d")
ax.plot_surface(meshed_slopes, meshed_intercepts, errors.reshape(1, meshed_slopes.shape[0]), cmap = cm.autumn_r)

Surface Plot with MatplotLib

But when I try to do the same using Plotly I get a blank graph.

This is the code am using to plot the surface plot-

import plotly.graph_objects as go 
import numpy as np

meshed_slopes, meshed_intercepts = np.meshgrid(slopes, intercepts)

fig = go.Figure(go.Surface(
    x = meshed_slopes,
    y = meshed_intercepts,
    z = errors.reshape(1, meshed_slopes.shape[0])
    ))

fig.show()

Graph with Plotly

How can I fix this?

Thanks in advance!!!

CodePudding user response:

Since you haven't provided the data so we can take a look I'm going to explain what plotly needs to make the plot work :

  • x and y needs to be both (n,) shape and same shape
  • z should be a matrix or a table with (n,n) size

I would suggest a dataframe as it might be easier for you to create everything

(Since I have low rep, I can't write comments so I'm posting this as an answear)

CodePudding user response:

Make sure that x, y, z are 2D arrays.

import plotly.graph_objects as go
import numpy as np

x, y = np.mgrid[-2:2:50j, -2:2:50j]
z = np.cos(x**2   y**2)
fig = go.Figure([
    go.Surface(x=x, y=y, z=z)
])
fig

enter image description here

  • Related