Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
blaylockbk / timer_decorator.py
Last active July 10, 2021 16:59
A decorator to time a function execution time
def timer(func):
"""
A decorator to time a function execution time.
Based on https://twitter.com/pybites/status/1387691670658068481?s=20
Parameters
----------
func : function
The function you wish to time.
@blaylockbk
blaylockbk / Path_expand.py
Last active July 10, 2021 16:47
replace environment variables in Path object
import os
from pathlib import Path
import warnings
# Create a new method for Path objects called `expand`, which fully
# expands the Path object with the given environment variables.
def _expand(self, *, strict=True):
"""
Fully expand and resolve the Path with the given environment variables.
@blaylockbk
blaylockbk / add_fig_letters.py
Created March 15, 2021 16:18
Add figure letters to matplotlib axes
def add_fig_letters(axes, offset=.07, facecolor='#f9ecd2', **kwargs):
"""
Add a figure letter to top-left corner for all axes
Like is done in a publication figure, all axes are labeled with a
letter so individual axes can be referred to from the text.
Paramters
---------
axes : list
@blaylockbk
blaylockbk / ipython_config.py
Created September 28, 2020 21:42
Don't let Jupyter Notebook matplotlib images output with transparency (when you copy it)
# Add this to your ~/.ipython/profile_default/ipython_config.py
# file so that when you copy a matplotlib plot from JupyterLab
# it will not copy the transparency.
c = get_config()
c.InlineBackend.print_figure_kwargs={'facecolor' : "w"}
try:
(do something)
except Exception as e:
print(f"WARNING: {e}")
@blaylockbk
blaylockbk / nearest_latlon_index.py
Created July 27, 2020 20:28
I often have xarray datasets with latitude and longitude coordinates (not as xarray dimensions). When I need to pluck values from a point nearest to a specific lat/lon coordinate (like a weather station), this is what I use...
import numpy as np
import xarray as xr
def to_180(lon):
"""
Wrap longitude from degrees [0, 360] to degrees [-180, 180].
An alternative method is
lon[lon>180] -= 360
@blaylockbk
blaylockbk / matplotlib_sequential_color_plot.py
Created July 13, 2020 21:45
Matplotlib's standard color cylce is ok if your data lines are distinct, but if each line is related to the others, then it is best to use a sequential color cycle.
a = np.arange(0, 3*np.pi, .1)
loops = range(5)
# Choose a colormap and create a list of colors with same length as our loop.
cmap = plt.get_cmap("YlGnBu")
colors = [cmap(i) for i in np.linspace(.15, .85, len(loops))]
fig, (ax1, ax2) = plt.subplots(1,2)
@blaylockbk
blaylockbk / force_do_not_print.py
Created July 13, 2020 17:46
When you have a function that insists on printing something, but you don't want it to print anything, do this...
## Based on https://stackoverflow.com/a/46129367/2383070
import os
import contextlib
def test_print(a):
print(f'2 * {a} =')
return 2*a
# Do not print the print statement in the function:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import ticker
coins = ['penny', 'nickle', 'dime', 'quarter']
worth = np.array([.01, .05, .10, .25])
values = [worth*i for i in range(1,6)]
# I like this example from the matplotlib cheatsheets
# https://github.com/matplotlib/cheatsheets
X = np.random.normal(-1, 1, 10_000)
Y = np.random.normal(-1, 1, 10_000)
plt.scatter(X, Y, 50, color="0.1", lw=2)
plt.scatter(X, Y, 50, color="1.0", lw=0)
plt.scatter(X, Y, 40, 'C1', lw=0, alpha=.1)
plt.gca().set_facecolor('.95')