Last active
July 27, 2023 01:57
-
-
Save rlcamp/17fc9bbd95e79dbeb72ab2cedab5ba0c to your computer and use it in GitHub Desktop.
using matplotlib to plot data vs unix time with yaxis_date is ungoogleable
This file contains 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
#!/usr/bin/env python3 | |
import sys | |
import os | |
def plot_image_vs_time(data, timestamps, x0, dx, xlabel, title=None): | |
import datetime | |
try: | |
import numpy | |
import matplotlib | |
except: | |
print('warning: plotting skipped, please "pip3 install matplotlib" or the equivalent on your OS') | |
exit() | |
matplotlib.use('pdf') | |
import matplotlib.pyplot | |
T, X = data.shape | |
if T < 2: raise RuntimeError('need multiple rows of pixels to plot') | |
if len(timestamps) != T: raise RuntimeError('need one timestamp per row of pixels') | |
dt_mean = (timestamps[T - 1] - timestamps[0]) / (T - 1) | |
fig, ax = matplotlib.pyplot.subplots() | |
# assumes that timestamps[0] and x0 specify the CENTRE of the oldest leftmost pixel | |
extent = [x0 - 0.5 * dx, x0 + (X - 0.5) * dx, | |
matplotlib.dates.date2num(datetime.datetime.utcfromtimestamp(timestamps[T - 1] + 0.5 * dt_mean)), | |
matplotlib.dates.date2num(datetime.datetime.utcfromtimestamp(timestamps[0] - 0.5 * dt_mean)) ] | |
# aspect is calculated from extent to force square pixels on screen | |
pos = ax.imshow(data, extent=extent, aspect=abs(extent[1] - extent[0]) * data.shape[0] / (abs(extent[3] - extent[2]) * data.shape[1]), vmin=0, vmax=255) | |
ax.yaxis_date() | |
ax.set(xlabel=xlabel) | |
if title: | |
ax.set(title=title) | |
ax.title.set_size(10) | |
if (sys.stdout.isatty()): | |
fig.savefig('/tmp/out.pdf', bbox_inches='tight') | |
os.system('open /tmp/out.pdf 2>/dev/null') | |
else: fig.savefig(sys.stdout.buffer, bbox_inches='tight') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment