Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

4D Density Plot in Python

I am looking to plot some density maps from some grid-like data:

X,Y,Z = np.mgrids[-5:5:50j, -5:5:50j, -5:5:50j]
rho = np.random.rand(50,50,50) #for the sake of argument

I am interested in producing an interpolated density plot as shown below, from Mathematica here, using Python.

Is there any solution in Matplotlib or another plotting suite for this sort of plot?

To be clear, I do not want a scatterplot of coloured points, which is not suitable the plot I am trying to make. I would like a 3D interpolated density plot, as shown below.

4D Density Plot

like image 726
Jack Rolph Avatar asked May 21 '26 07:05

Jack Rolph


1 Answers

Plotly

Plotly Approach from https://plotly.com/python/3d-volume-plots/ uses np.mgrid

import plotly.graph_objects as go
import numpy as np
X, Y, Z = np.mgrid[-8:8:40j, -8:8:40j, -8:8:40j]
values = np.sin(X*Y*Z) / (X*Y*Z)

fig = go.Figure(data=go.Volume(
    x=X.flatten(),
    y=Y.flatten(),
    z=Z.flatten(),
    value=values.flatten(),
    isomin=0.1,
    isomax=0.8,
    opacity=0.1, # needs to be small to see through all surfaces
    surface_count=17, # needs to be a large number for good volume rendering
    ))
fig.show()

screenshot of interactive output

Pyvista

Volume Rendering example: https://docs.pyvista.org/examples/02-plot/volume.html#sphx-glr-examples-02-plot-volume-py

3D-interpolation code you might need with pyvista: interpolate 3D volume with numpy and or scipy

like image 136
Mark H Avatar answered May 22 '26 19:05

Mark H