Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a 3D surface plot in Plotly

I want to create a 3D surface plot in Plotly by reading the data from an external file. Following is the code I am using:

import numpy as np
import plotly.graph_objects as go 
import plotly.express as px


data = np.genfromtxt('values.dat', dtype=float)

# The shape of X, Y and Z is (10,1)
X = data[:,0:1] 
Y = data[:,1:2]
Z = data[:,2:3]

fig = go.Surface(x=X, y=Y, z=Z, name='Surface plot', colorscale=px.colors.sequential.Plotly3)
plot(fig)

The above code does not produce any surface plot. What changes has to be made to create a surface plot?

like image 261
Aim Avatar asked Jul 26 '26 05:07

Aim


1 Answers

From plotly figure reference:

The data the describes the coordinates of the surface is set in z. Data in z should be a 2D list. Coordinates in x and y can either be 1D lists or {2D arrays}

I have an example data set. It contains three columns (x,y,z).

import plotly.graph_objects as go
import pandas as pd
import numpy as np
from scipy.interpolate import griddata


df = pd.read_csv('./test_data.csv')

x = np.array(df.lon)
y = np.array(df.lat)
z = np.array(df.value)


xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)

X,Y = np.meshgrid(xi,yi)

Z = griddata((x,y),z,(X,Y), method='cubic')



fig = go.Figure(go.Surface(x=xi,y=yi,z=Z))
fig.show()

Reference Page: https://plotly.com/python/reference/surface/

figure

like image 159
Akroma Avatar answered Jul 28 '26 17:07

Akroma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!