Skip to content

Instantly share code, notes, and snippets.

@lukauskas
Last active November 24, 2021 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukauskas/1df69094637ff6699e30f1ef7144ecd3 to your computer and use it in GitHub Desktop.
Save lukauskas/1df69094637ff6699e30f1ef7144ecd3 to your computer and use it in GitHub Desktop.
Code-snippets that I google every day.

Initialisation of notebook (suitable for print)

%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import os
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from tqdm import tqdm
sns.set_palette('Dark2')
sns.set_context('paper')
sns.set_style({'axes.axisbelow': True, 
               'axes.edgecolor': '.15',
               'axes.facecolor': 'white',
               'axes.grid': True, 
               'axes.labelcolor': '.15', 
               'figure.facecolor': 'white', 
               'grid.color': '.15',
               'grid.linestyle': ':', 
               'grid.alpha': .5, 
               'image.cmap': 'Greys', 
               'legend.frameon': False, 
               'legend.numpoints': 1, 
               'legend.scatterpoints': 1,
               'lines.solid_capstyle': 'butt', 
               'axes.spines.right': False, 
               'axes.spines.top': False,  
               'text.color': '.15',  
               'xtick.top': False, 
               'ytick.right': False, 
               'xtick.color': '.15',
               'xtick.direction': 'out', 
               'ytick.color': '.15', 
               'ytick.direction': 'out', 
              })


import matplotlib

FONT_SIZE_PT = 5
matplotlib.rcParams['font.family'] = 'Arial'
matplotlib.rcParams['font.size'] = FONT_SIZE_PT
matplotlib.rcParams['axes.labelsize'] = FONT_SIZE_PT
matplotlib.rcParams['axes.titlesize'] = FONT_SIZE_PT
matplotlib.rcParams['figure.titlesize'] = FONT_SIZE_PT
matplotlib.rcParams['xtick.labelsize'] = FONT_SIZE_PT
matplotlib.rcParams['ytick.labelsize'] = FONT_SIZE_PT
matplotlib.rcParams['legend.fontsize'] = FONT_SIZE_PT
matplotlib.rcParams['legend.title_fontsize'] = FONT_SIZE_PT

matplotlib.rcParams['xtick.major.size'] = matplotlib.rcParams['ytick.major.size'] = 2
matplotlib.rcParams['xtick.major.width'] = matplotlib.rcParams['ytick.major.width'] = 0.5


matplotlib.rcParams['xtick.minor.size'] = matplotlib.rcParams['ytick.minor.size'] = 1

matplotlib.rcParams['xtick.minor.width'] = matplotlib.rcParams['ytick.minor.width'] = 0.5

matplotlib.rcParams['axes.linewidth'] = 0.5
matplotlib.rcParams['lines.linewidth'] = 0.5
matplotlib.rcParams['grid.linewidth'] = 0.25
matplotlib.rcParams['patch.linewidth'] = 0.25
matplotlib.rcParams['lines.markeredgewidth'] = 0.25
matplotlib.rcParams['lines.markersize'] = 2

FIVE_MM_IN_INCH = 0.19685
DPI = 600
matplotlib.rcParams['figure.figsize'] = (10 * FIVE_MM_IN_INCH, 9 * FIVE_MM_IN_INCH)
matplotlib.rcParams['savefig.dpi'] = DPI
matplotlib.rcParams['figure.dpi'] = DPI // 4


#http://phyletica.org/matplotlib-fonts/
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42

Matplotlib figures to multiple pdf pages:

from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('multipage_pdf.pdf') as pdf:
  # Plot figure here
  
  pdf.savefig()  # saves the current figure into a pdf page
  plt.close()

Saving with tight-layout (preventing cropping)

plt.savefig(filename, bbox_inches = 'tight')

Legend outside of plot

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

Plotting in both data and axis coordinates:

import matplotlib.transforms as transforms
trans = transforms.blended_transform_factory(
    ax.transData, ax.transAxes)
ax.text(data_coord, axis_coord, 'text',
      transform=trans)

Annotating with correlation coefficient and p-value. Can be used with seaborn.FacetGrid

from scipy.stats import pearsonr, spearmanr
def annotate_with_corrcoef(x, y, color=None, method='spearmanr', ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    
    if method == 'spearmanr':
        coef, p = spearmanr(x, y)
    elif method == 'pearsonr':
        coef, p = pearsonr(x, y)
    else:
        raise NotImplementedError('method {!r} not implemented'.format(method))
        
    ax.text(0.05, 0.95, f'{method}={coef:.4f}, p={p:.4f}', 
            horizontalalignment='left', 
            verticalalignment='top', 
            transform=ax.transAxes,
            **kwargs)
    

Seaborn's trick for determining annotation text color (taken from https://github.com/mwaskom/seaborn/blob/5403666b6cb0f4bfe87041f6a91053aa0bce32ea/seaborn/matrix.py#L242):

from seaborn.utils import relative_luminance
lum = relative_luminance(color)
text_color = "k" if lum > .408 else "w"

Comparing two PDF images from StackOverflow

compare -density 300 a.pdf b.pdf delta.pdf

rpy2 inline plots in jupyter:

from contextlib import contextmanager
from rpy2.robjects.lib import grdevices
from IPython.display import Image, display

@contextmanager
def r_inline_plot(width=600, height=600, dpi=100):

    with grdevices.render_to_bytesio(grdevices.png, 
                                     width=width,
                                     height=height, 
                                     res=dpi) as b:

        yield

    data = b.getvalue()
    display(Image(data=data, format='png', embed=True))

rpy2 Conversion

from rpy2.robjects import pandas2ri, numpy2ri
from rpy2 import robjects

with robjects.conversion.localconverter(robjects.default_converter + pandas2ri.converter):
    pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment