Skip to content

Instantly share code, notes, and snippets.

@guenp
Last active August 29, 2015 14:10
Show Gist options
  • Save guenp/5b89ed513046d0029753 to your computer and use it in GitHub Desktop.
Save guenp/5b89ed513046d0029753 to your computer and use it in GitHub Desktop.
data analysis
# derivative
def dydx(x,y):
dy = np.zeros(y.shape,np.float) #we know it will be this size
dy[0:-1] = np.diff(y)/np.diff(x)
dy[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
return dy
legend(loc='center left', bbox_to_anchor=(1, 0.5))
#nice default plot props
%matplotlib inline
matplotlib.rcParams['font.size'] = 21
matplotlib.rcParams['figure.figsize'] = (12.0, 8.0)
matplotlib.rcParams['legend.fontsize'] = 21
matplotlib.rcParams['figure.figsize'] = [6, 6]
matplotlib.rcParams['xtick.major.pad']='3'
matplotlib.rcParams['ytick.major.pad']='3'
matplotlib.rcParams['xtick.major.width'] = 2
matplotlib.rcParams['ytick.major.width'] = 2
matplotlib.rcParams['axes.linewidth'] = 2
matplotlib.rcParams['mathtext.fontset'] = 'stixsans'
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
'''
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero
Input
-----
cmap : The matplotlib colormap to be altered
start : Offset from lowest point in the colormap's range.
Defaults to 0.0 (no lower ofset). Should be between
0.0 and `midpoint`.
midpoint : The new center of the colormap. Defaults to
0.5 (no shift). Should be between 0.0 and 1.0. In
general, this should be 1 - vmax/(vmax + abs(vmin))
For example if your data range from -15.0 to +5.0 and
you want the center of the colormap at 0.0, `midpoint`
should be set to 1 - 5/(5 + 15)) or 0.75
stop : Offset from highets point in the colormap's range.
Defaults to 1.0 (no upper ofset). Should be between
`midpoint` and 1.0.
'''
cdict = {
'red': [],
'green': [],
'blue': [],
'alpha': []
}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack([
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True)
])
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict['red'].append((si, r, r))
cdict['green'].append((si, g, g))
cdict['blue'].append((si, b, b))
cdict['alpha'].append((si, a, a))
newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
plt.register_cmap(cmap=newcmap)
return newcmap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment