Last active
April 21, 2021 10:45
-
-
Save maxnoe/3deef353cf377245f28a04f32dee6ee8 to your computer and use it in GitHub Desktop.
Plotting a secondary MJD date axis with matplotlib ≥ 3.1
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
import matplotlib.pyplot as plt | |
import numpy as np | |
from astropy.time import Time | |
import astropy.units as u | |
t = Time.now() + np.linspace(0, 30, 30) * u.day | |
# plot something vs time normally using a list of datetimes as x values | |
fig, ax = plt.subplots(constrained_layout=True) | |
ax.plot(t.to_datetime(), np.random.normal(80, 10, 30)) | |
for l in ax.get_xticklabels(): | |
l.set_ha('right') | |
l.set_rotation(30) | |
# create the secondary axis showing mjd at the top | |
def plot2mjd(t): | |
'''Convert from matplotlib plot date to mjd''' | |
return Time(t, format="plot_date").mjd | |
def mjd2plot(mjd): | |
'''Convert from mjd to matplotlib plot''' | |
return Time(mjd, format="mjd").plot_date | |
mjd_ax = ax.secondary_xaxis('top', functions=(plot2mjd, mjd2plot)) | |
mjd_ax.set_xlabel('MJD') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
