'plotly 3D Topographical 3D Surface Plot with pandas dataframe
I have a coordenates points cloud in a padas dataframe
Following, I want to plot a ploty surface diagram but Surface method needs a 2D array in z param and i don't know how to build it.
go.Figure(data=[go.Surface(z=z, x=x, y=y)])
Solution 1:[1]
I think you need to grid your data first. I created an example from your data.
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from scipy.interpolate import griddata
#Read data
data = pd.read_csv('data.txt', header=0, delimiter='\t')
#Create meshgrid for x,y
xi = np.linspace(min(data['x']), max(data['x']), num=100)
yi = np.linspace(min(data['y']), max(data['y']), num=100)
x_grid, y_grid = np.meshgrid(xi,yi)
#Grid data
z_grid = griddata((data['x'],data['y']),data['z'],(x_grid,y_grid),method='cubic')
# Plotly 3D Surface
fig = go.Figure(go.Surface(x=x_grid,y=y_grid,z=z_grid,
colorscale='viridis',showlegend=True)
)
fig.show()
3D surface from your example data
You can use different methods for gridding (cubic, linear, nearest) https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html
Solution 2:[2]
It's definitely a bad design that go.Surface doesn't support directly using DataFrames as parameters. Imagine you swapped x and y, for example: x=df.index, y=df.columns, z=df.values. You won't notice that your x-axis data isn't fully displayed if you don't scrutinize it carefully. That's because you reversed x and y, which gives you the wrong result!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | Joe Huang |

