Plot 4D Contour in Python (X,Y,Z + Data)

10.2k views Asked by At

I have a large set of measurements that I want to visualize in 4D using matplotlib in Python. Currently, my variables are arranged in this way:

x = np.array(range(0, v1))
y = np.array(range(0, v2))
z = np.array(range(0, v3))

I have C which is a 3D array containing measurement values for each combination of the previous variables. So it has a dimension of v1*v2*v3.

Currently, I visualize my measurements using contourf function and I plot that for each z value. This results in 3D contour plot i.e. 2D + color map for the values. Now, I want to combine all the variables and look at the measurements in 4D dimensions (x, y, z, and color corresponding to the measurement value). What is the most efficient way to do this in python?

3

There are 3 answers

0
Sameeresque On

A 4D plot with (x,y,z) on the axis and the fourth being color can be obtained like so:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.array(range(0, 50))
y = np.array(range(0, 50))
z = np.array(range(0, 50))
colors = np.random.standard_normal(len(x))
img = ax.scatter(x, y, z, c=colors, cmap=plt.hot())
fig.colorbar(img)
plt.show()

enter image description here

0
Alexander Korovin On

Regarding to @Sameeresque answer, I think the question was about a 4D graph like this (three coordinates x, y, z and a color as the fourth coordinate):

enter image description here

import numpy as np
import matplotlib.pyplot as plt

# only for example, use your grid
z = np.linspace(0, 1, 15)
x = np.linspace(0, 1, 15)
y = np.linspace(0, 1, 15)

X, Y, Z = np.meshgrid(x, y, z)

# Your 4dimension, only for example (use yours)
U = np.exp(-(X/2) ** 2 - (Y/3) ** 2 - Z ** 2)

# Creating figure
fig = plt.figure()
ax = plt.axes(projection="3d")

# Creating plot
ax.scatter3D(X, Y, Z, c=U, alpha=0.7, marker='.')
plt.show()
0
Yubin Hu On

A simple way to visualize your 4D function, call it W(x, y, z), could be producing a gif of the cross-section contour plots along the z-axis.

Package plot4d could help you do it. An example plotting an isotropic 4D function:

from plot4d import plotter
import numpy as np
plotter.plot4d(lambda x,y,z:x**2+y**2+z**2, np.linspace(0,1,20), wbounds=(0,3), fps=5)

The code above generates this gif: Cross-section plot