Skip to content

Instantly share code, notes, and snippets.

@maxnoe
Last active April 21, 2021 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxnoe/3deef353cf377245f28a04f32dee6ee8 to your computer and use it in GitHub Desktop.
Save maxnoe/3deef353cf377245f28a04f32dee6ee8 to your computer and use it in GitHub Desktop.
Plotting a secondary MJD date axis with matplotlib ≥ 3.1
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()
@maxnoe
Copy link
Author

maxnoe commented Apr 21, 2021

Result:
mjd_axis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment