Created
January 27, 2026 13:58
-
-
Save HealthyPear/25178d09e9a929ce6d09d020af5d23f7 to your computer and use it in GitHub Desktop.
Plot radio data from WCS in a cool way and export it also to Tikz format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pathlib import Path | |
| import astropy.units as u | |
| import matplot2tikz | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import seaborn as sns | |
| from astropy.coordinates import SkyCoord | |
| from astropy.io import fits | |
| from astropy.nddata import Cutout2D | |
| from astropy.wcs import WCS | |
| sns.set_theme(context="talk", | |
| style="whitegrid", | |
| palette="deep", | |
| font_scale=1, | |
| color_codes=True, | |
| rc={ | |
| "font.family": "Fira Sans", | |
| "font.weight": "normal", | |
| "font.style": "normal", | |
| } | |
| ) | |
| with fits.open("path/to/file.fits") as hdul: | |
| hdu = hdul[0] | |
| wcs = WCS(hdu.header) | |
| data = hdu.data | |
| # Define center in sky coordinates | |
| center = SkyCoord( | |
| l=43.27 * u.deg, | |
| b=-0.19 * u.deg, | |
| frame="galactic" | |
| ) | |
| cutout = Cutout2D( | |
| data, | |
| position=center, | |
| size=2*(7 * u.arcmin,), | |
| wcs=wcs | |
| ) | |
| data = cutout.data | |
| wcs = cutout.wcs | |
| fig, ax = plt.subplots(subplot_kw={"projection":wcs}) | |
| vmin=data.min() | |
| vmax=data.max() | |
| mappable = ax.imshow(data, vmin=vmin, vmax=vmax, origin="lower", cmap="mako") | |
| ax.grid(color="white", ls="solid", alpha=0.5) | |
| levels = np.linspace(vmin, vmax, 5) | |
| contours = ax.contour(data, levels=levels, colors="white", alpha=0.5) | |
| ax.set(xlabel="Galactic Longitude", ylabel="Galactic Latitude") | |
| cbar = fig.colorbar(mappable, ax=ax, label=hdu.header["BUNIT"]) | |
| ax.clabel(contours, | |
| fontsize=15, | |
| fmt="%.1f") | |
| # cbar.add_lines(contours) | |
| fig.savefig("plot.png") # save a regular PNF file | |
| # Export to Tikz format with matplot2tikz | |
| #see https://github.com/ErwindeGelder/matplot2tikz | |
| # Set same figure dimensions as from matplotlib | |
| pos = ax.get_position() | |
| fig_width = fig.get_figwidth() | |
| fig_height = fig.get_figheight() | |
| axes_width = (pos.x1 - pos.x0) * fig_width | |
| axes_height = (pos.y1 - pos.y0) * fig_height | |
| # Then save with those dimensions | |
| matplot2tikz.save("plot.tex", | |
| axis_width=f"{axes_width}in", | |
| axis_height=f"{axes_height}in") | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment