Interactive 3D plot of a Planck map with Matplotlib

python
astrophysics
Published

May 20, 2024

This is an update of my older tutorial

Unfortunately I was not able to make Mayavi properly plot the data, rerunning the same code would give a map that looked like uniform noise.

This test instead uses matplotlib, unfortunately this is extremely slow, and the output map is really slow to rotate or interact at all. Anyway it is possible to tweak xsize,ysize to change the resolution as a trade-off between resolution and interactivity.

#from mayavi import mlab
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
# load a Planck map, Kcmb -> mKcmb
m = hp.read_map("HFI_SkyMap_100_2048_R3.01_full.fits", 0) * 1e3
nside = hp.npix2nside(len(m))
vmin = -1; vmax = 1
# size of the grid
xsize = ysize = 500
theta = np.linspace(np.pi, 0, ysize)
phi = np.linspace(-np.pi, np.pi, xsize)
longitude = np.radians(np.linspace(-180, 180, xsize))
latitude = np.radians(np.linspace(-90, 90, ysize))
# project the map to a rectangular matrix xsize x ysize
PHI, THETA = np.meshgrid(phi, theta)
grid_pix = hp.ang2pix(nside, THETA, PHI)
grid_map = m[grid_pix]
# Create a sphere
r = 1
x = r*np.sin(THETA)*np.cos(PHI)
y = r*np.sin(THETA)*np.sin(PHI)
z = r*np.cos(THETA)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
from matplotlib import cm
grid_map = np.clip(grid_map, -1, 1)
grid_map -= grid_map.min()
grid_map /= grid_map.max()
ax.plot_surface( x, y, z, cstride=1, rstride=1, facecolors=cm.jet(grid_map) )
# Set an equal aspect ratio
ax.set_aspect('equal')
plt.show()

Screenshot of the 3D plot with matplotlib