Skip to content

Commit

Permalink
Better time axis formatting for plots
Browse files Browse the repository at this point in the history
  • Loading branch information
claudiodsf committed Apr 2, 2024
1 parent 1e500ff commit cfe9888
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 23 deletions.
11 changes: 3 additions & 8 deletions requake/plot/plot_slip.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import cm
from matplotlib import colors
import numpy as np
from .plot_utils import format_time_axis
from ..families.families import FamilyNotFoundError, read_selected_families
from ..formulas.slip import mag_to_slip_in_cm
from ..config.rq_setup import rq_exit
Expand All @@ -37,13 +37,6 @@ def plot_slip(config):
logger.error(m)
rq_exit(1)
fig, ax = plt.subplots(figsize=(8, 4))
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.grid(True)
ax.tick_params(which='both', top=True, labeltop=True)
ax.tick_params(axis='x', which='both', direction='in')

Expand All @@ -64,6 +57,8 @@ def plot_slip(config):
lw=1, marker='o', color=cmap(norm(fn % 10)),
label=label)
lines.append(line)
# time axis formatting must be done here, before setting limits below
format_time_axis(ax, which='xaxis')
# get limits, that we will re-apply later
xlim = ax.get_xlim()
ylim = ax.get_ylim()
Expand Down
19 changes: 4 additions & 15 deletions requake/plot/plot_timespans.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import cm
from matplotlib import colors
import numpy as np
from .plot_utils import format_time_axis
from ..families.families import FamilyNotFoundError, read_selected_families
from ..config.rq_setup import rq_exit
logger = logging.getLogger(__name__.rsplit('.', maxsplit=1)[-1])
Expand All @@ -36,13 +36,6 @@ def plot_timespans(config):
logger.error(m)
rq_exit(1)
fig, ax = plt.subplots(figsize=(8, 8))
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.grid(True)
ax.tick_params(which='both', top=True, labeltop=True)
ax.tick_params(axis='x', which='both', direction='in')

Expand All @@ -69,13 +62,6 @@ def plot_timespans(config):
'but "distance_from_lon" and/or "distance_from_lat" '
'are not specified')
rq_exit(1)
if sort_by == 'time':
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.yaxis.set_major_locator(years)
ax.yaxis.set_major_formatter(yearsFmt)
ax.yaxis.set_minor_locator(months)
for family in families:
fn = family.number
label = (
Expand Down Expand Up @@ -105,6 +91,9 @@ def plot_timespans(config):
times, yvals, lw=1, marker='o', color=cmap(norm(fn % 10)),
label=label)
lines.append(line)
format_time_axis(ax, which='xaxis')
if sort_by == 'time':
format_time_axis(ax, which='yaxis')
ax.set_xlabel('Time')
ax.set_ylabel(ylabel)
sm = cm.ScalarMappable(cmap=cmap, norm=norm)
Expand Down
42 changes: 42 additions & 0 deletions requake/plot/plot_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding: utf8 -*-
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Plot utils.
:copyright:
2021-2024 Claudio Satriano <[email protected]>
:license:
GNU General Public License v3.0 or later
(https://www.gnu.org/licenses/gpl-3.0-standalone.html)
"""
import matplotlib.dates as mdates


def format_time_axis(ax, which='both'):
"""
Format the time axis of a Matplotlib plot.
"""
if which == 'both':
axes = [ax.xaxis, ax.yaxis]
elif which == 'xaxis':
axes = [ax.xaxis]
elif which == 'yaxis':
axes = [ax.yaxis]
else:
raise ValueError(f'Invalid value for "which": {which}')
for axis in axes:
dmin, dmax = axis.get_data_interval()
timespan = dmax-dmin
if timespan > 365:
_major_locator = mdates.YearLocator() # every year
_major_fmt = mdates.DateFormatter('%Y')
_minor_locator = mdates.MonthLocator() # every month
else:
_major_locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
_major_fmt = mdates.ConciseDateFormatter(_major_locator)
_minor_locator = mdates.DayLocator() # every day
axis.set_major_locator(_major_locator)
axis.set_major_formatter(_major_fmt)
axis.set_minor_locator(_minor_locator)
axis.grid(True, which='major', linestyle='--', color='0.5')
axis.grid(True, which='minor', linestyle=':', color='0.8')

0 comments on commit cfe9888

Please sign in to comment.