Skip to content

Instantly share code, notes, and snippets.

@koreyou
Created January 7, 2018 07:58
Show Gist options
  • Save koreyou/e74c22b1be5cc026338db6a3ae8f25c5 to your computer and use it in GitHub Desktop.
Save koreyou/e74c22b1be5cc026338db6a3ae8f25c5 to your computer and use it in GitHub Desktop.
ipython startup (deprecated)
# coding: utf-8
"""
This is the ipython startup script that I used to use in university.
(but not anymore)
Place it in ~/.ipython/profile_default/startup/startup.py for it to work
"""
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib
import itertools as itr
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itr.tee(iterable)
next(b, None)
return itr.izip(a, b)
def homogeneous(arr):
"""
Create 4xN homogeneous representation matrix from 3xN matrix.
Do NOT pass Nx3 matrix.
"""
arr = np.asarray(arr)
arr = np.reshape(arr, (3, -1))
return np.vstack((arr, np.ones((1, arr.shape[1]))))
def unhomogeneous(arr):
"""
From 4xN homogeneous, create 3xN normal representation.
Will NOT warn even if 4th element is non-one.
"""
arr = np.asarray(arr)
arr = np.reshape(arr, (4,-1))
return arr[0:3, :]
def hide_spines():
"""
Hides the top and rightmost axis spines from view for all active
figures and their respective axes.
Copyright Stackoverflow http://stackoverflow.com/questions/3439344/setting-spines-in-matplotlibrc
Modified 2015/1/24 by Yuta Koreeda
"""
# Retrieve a list of all current figures.
figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
for figure in figures:
# Get all Axis instances related to the figure.
for ax in figure.canvas.figure.get_axes():
# Disable spines.
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Disable ticks.
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Change spine position
ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_smart_bounds(False)
ax.spines['left'].set_smart_bounds(False)
def boxplot_kikai(x, vert_=True, positions_=None, widths_=None, usermedians_=None, conf_intervals_=None, showmeans_=False, labels_=None):
"""
Draw a boxplot in Kikai-ka style
Whisker shows min-max.
Based on matplotlib.pyplot.boxplot
"""
bp = plt.boxplot(x,notch=False, sym='', vert=vert_, whis=200, positions=positions_, widths=widths_, patch_artist=True, bootstrap=None, usermedians=usermedians_, conf_intervals=conf_intervals_, meanline=True, showmeans=showmeans_, showcaps=True, showbox=True, showfliers=False, boxprops=dict(linewidth=1.5), labels=labels_, flierprops=None)
for med_artist in bp['medians']:
plt.setp(med_artist, color='black', linewidth=1.5, solid_capstyle="projecting")
for caps_artist in bp['caps']:
plt.setp(caps_artist, color='black',linewidth=1.5)
for whisk_artist in bp['whiskers']:
plt.setp(whisk_artist,color='black', linestyle='-', linewidth=1.5, solid_capstyle="projecting")
return bp
def freedmanDiaconisRule(x):
"""
Calculate appropriate number of bins for histogram using Freedman-Diaconis' Rule
"""
iqr = np.subtract(*np.percentile(x, [75, 25]))
h = 2 * iqr / math.pow(len(x), 1.0/ 3.0)
return math.ceil((np.max(x) - np.min(x)) / h)
def roundToSignificant(val, dig):
assert dig >=1, "Significant digits must at least 1 digit"
if val != 0:
return round(val, -int(math.floor(math.log10(abs(val))))+ (dig - 1))
else:
itms = list("0.") + ["0" for i in range(dig - 1)]
return "".join(itms)
def boxplotWithValues(arr_of_arr, significant_digits=2):
"""
Draw boxplot with value annotations
Whiskers show min-max
"""
plt.boxplot(arr_of_arr, showmeans=True, whis=200)
medians = np.median(arr_of_arr, axis=1)
means = np.mean(arr_of_arr, axis=1)
for i in range(len(arr_of_arr)):
plt.annotate(str(roundToSignificant(medians[i], significant_digits)), xy=(i + 0.9, medians[i]), horizontalalignment='right', verticalalignment='center')
plt.annotate(str(roundToSignificant(means[i], significant_digits)), xy=(i + 0.9, means[i]), horizontalalignment='right', verticalalignment='center')
def pause():
"""
Let matplotlib draw graph.
"""
plt.pause(1.e-6)
def toMillisec(hour, minute, second):
return ((hour * 60 + minute) * 60 + second) * 1000
def in2px(inches, fig=None):
import matplotlib.pyplot as plt
if fig is None:
fig = plt.gcf()
return inches * fig.get_dpi()
def pt2in(point): return point/72.0
def pt2px(point, fig=None):
return in2px(inches(point), fig)
def mm2inch(millimeters):
return 0.0393700787 * millimeters
def inch2mm(inches):
return 25.4 * inches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment