Skip to content

Instantly share code, notes, and snippets.

# For overlaying two colorbars on the same figure
plt.rcParams['hatch.color'] = (1, 1, 1, .33)
plt.rcParams['hatch.linewidth'] = 8
plt.bar([1,2], [2,5], color='.1', label='first')
plt.bar([1,2], [3,4], hatch='/', alpha=.33, color='g', label='second')
plt.legend()
@blaylockbk
blaylockbk / update_file_home_path.py
Last active March 18, 2020 19:11
For a file name that begins with '~' or an environment varialbe, update the file name with the environment home directory.
#==========================================================================
## Simple method, just deal with the '~' notation for home
#==========================================================================
import os
FILE = "~/path/to/file.data"
FILE = FILE.replace('~', os.environ['HOME'])
#==========================================================================
#==========================================================================
## More involved, but deals with other environment variables
@blaylockbk
blaylockbk / str_operator.py
Created February 5, 2020 21:12
Performs an operation when you have an operator as a string.
def str_operator(left, operator_str, right):
"""
Performs an operation when you have an operator as a string.
An alternative method is to use the `eval()` function, if you aren't
worried about the security vulnerabilities.
Example, `eval('a + b')` where a=5 and b=6 will result in 11.
Parameters
----------
@blaylockbk
blaylockbk / border.py
Created January 31, 2020 22:49
python function to extract the values around the border of an array
def border(array, corner=0, direction='cw'):
"""
Extract the values arround the border of a 2d array.
Default settings start from top left corner and move clockwise.
Corners are only used once.
Parameters
----------
array : array_like
@blaylockbk
blaylockbk / datetime string formatting.py
Last active March 26, 2021 20:54
Methods to format python datetime object as strings
from datetime import datetime
DATE = datetime(2019, 1, 1, 12, 35)
print(DATE)
# The most common way, with formatters
# https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
d1 = DATE.strftime('%Y %b %d, %H:%M')
print('The date and time is %s' % d1)
@blaylockbk
blaylockbk / infer_interval_breaks
Created November 8, 2019 21:23
infer interval and create new x and y grid to plot data with pcolormesh without loosing the last row and column (code snipet from xarray/plot/utils)
def xr_infer_interval_breaks(coord, axis=0):
"""
Code from xarray: (github/pydata/xarray/plot/utils)
Usage: if x is a 2d array of longitudes...
x = _infer_interval_breaks(x, axis=1)
x = _infer_interval_breaks(x, axis=0) # repeat for second axis
"""
deltas = 0.5 * np.diff(coord, axis=axis)
first = np.take(coord, [0], axis=axis) - np.take(deltas, [0], axis=axis)
last = np.take(coord, [-1], axis=axis) + np.take(deltas, [-1], axis=axis)
@blaylockbk
blaylockbk / download_GOES_AWS.py
Created August 30, 2019 17:31
View and download GOES data on AWS with s3fs
# Brian Blaylock
# Requres `s3fs`
# Website: https://s3fs.readthedocs.io/en/latest/
# In Anaconda, download via conda-forge.
import s3fs
# Use the anonymous credentials to access public data
fs = s3fs.S3FileSystem(anon=True)
@blaylockbk
blaylockbk / genfromtxt_encoding.py
Created February 15, 2019 15:52
numpy genfromtxt mixed numbers and strings encoding
# For a .csv file where there are mixed data types (column of floats, column of strings i.e. Dates)
# then if you set the encoding='UTF-8', the dates or column of strings will return as a string
# rather than a "bytes" type.
FILENAME = 'some_csv_file.csv'
data = np.genfromtxt(FILENAME, delimiter=',', names=True, dtype=None, encoding='UTF-8')
# Since names is set to True, the returned data can be accessed by header column name.
# If a column is labeled 'DATES', you can access the dates like you do a dictionary...
get_dates = data['DATES']
@blaylockbk
blaylockbk / colors.py
Created February 4, 2019 21:41
List of colors from a color map
import matplotlib
# Generate a list of colors
cmap = matplotlib.cm.get_cmap('Spectral')
# Retrieve 19 colors from the colormap
colors = cmap(np.arange(19)/19)
@blaylockbk
blaylockbk / progress.py
Created February 4, 2019 17:43
Print progress to show completion of a loop
# Print a progress bar for a loop completion
from time import sleep
F = range(10)
num = len(F)
for i in F:
sleep(1)
sys.stdout.write('\r%.1f%% Complete (%s of %s)' % (i/num*100, i, num))