How to use the seaborn.set_context function in seaborn

To help you get started, we’ve selected a few seaborn examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github IBM / Semantic-Search-for-Sustainable-Development / src / undp_experiments_3.py View on Github external
combined_prior_matches['cambodia_nbow'] = combined_prior_matches.pop('cambodia_template22')
combined_prior_matches['cambodia_tfidf'] = combined_prior_matches.pop('cambodia_template23')
combined_prior_matches['mauritius_google'] = combined_prior_matches.pop('mauritius1')
combined_prior_matches['mauritius_nbow'] = combined_prior_matches.pop('mauritius2')
combined_prior_matches['mauritius_tfidf'] = combined_prior_matches.pop('mauritius3')

countries = ['liberia', 'bhutan', 'namibia', 'cambodia', 'mauritius']
num_sentences = 30
for key in combined_prior_matches.keys():
    print('{0:10}  {1:10.5f}%'.format(key, combined_prior_matches[key][2][num_sentences]*100))
    #print('-------------------------------------------------------------------------------')
    
import matplotlib.pyplot as plt
import seaborn as sns
#%matplotlib inline
sns.set_context('talk')
sns.set_style("white")
plt.figure(figsize=(15,11))

i =0
for key in combined_prior_matches:
    if 'tfidf' in key:
        plt.plot(list(range(1, 31)), (np.asarray(sorted(combined_prior_matches[key][2]))*100)[:30], label = key.split('.')[0].split('_')[0].upper())
plt.legend(title = 'Country', bbox_to_anchor=(1.1, 0.45), loc=1, borderaxespad=10)
plt.title('Percent Matches Vs. Number of Sentences')
plt.xlabel('Number of Sentences')
plt.ylabel('Percent Matches with Policy Experts')
plt.yticks(np.arange(0, 55, 5))
#plt.savefig('matches_update_30.jpeg')
plt.show()

plt.figure(figsize=(15,11))
github noaa-oar-arl / MONET / monet / monet_accessor.py View on Github external
at 0 degrees.
        **kwargs :
            kwargs for the xarray.DataArray.plot.contourf function

        Returns
        -------
        type
            axes

        """
        from monet.plots.mapgen import draw_map
        from monet.plots import _dynamic_fig_size
        import matplotlib.pyplot as plt
        import cartopy.crs as ccrs
        import seaborn as sns
        sns.set_context('notebook')
        da = _dataset_to_monet(self._obj)
        crs_p = ccrs.PlateCarree()
        if 'crs' not in map_kws:
            map_kws['crs'] = crs_p
        if 'figsize' in kwargs:
            map_kws['figsize'] = kwargs['figsize']
            kwargs.pop('figsize', None)
        else:
            figsize = _dynamic_fig_size(da)
            map_kws['figsize'] = figsize
        if 'transform' not in kwargs:
            transform = crs_p
        else:
            transform = kwargs['transform']
            kwargs.pop('transform', None)
        ax = draw_map(**map_kws)
github tdamdouni / Pythonista / tasks / generate_tasks_graph-Moving-Electrons.py View on Github external
reduced_df_allDays = reduced_df.reindex(index=allDates_index, fill_value=0)
	
	# Transforming the dataframe index (DatetimeIndex object) to a regular pd.Series so "apply" can be used.
	# The Pandas "apply" method is used in this case to apply an "anonymous" function
	# (one we don't want to create a separate function for) to all the
	# components of the DataFrame/Series
	
	
	weekday_series = pd.Series(reduced_df_allDays.index, index = reduced_df_allDays.index).apply(lambda x: x.strftime('%a'))
	
	# Adding another column with string objects representing weekdays.
	reduced_df_allDays['weekday'] = weekday_series
	
	# Setting a pre-defined style from Seaborn
	sns.set_context('notebook')
	# Pandas plotting
	line_plot = reduced_df_allDays.plot(legend=False, title='Tasks Distribution - Next '+str(NUMBER_OF_DAYS)+' Days',
	y=['tasks'], kind='line')
	print("Generating Graph..")
	fig = line_plot.get_figure()
	fig.savefig(OUTPUT)
	print("Done.")
github MNGuenther / allesfitter / allesfitter / postprocessing / plot_violins.py View on Github external
MIT Kavli Institute for Astrophysics and Space Research, 
Massachusetts Institute of Technology,
77 Massachusetts Avenue,
Cambridge, MA 02109, 
USA
Email: maxgue@mit.edu
Web: www.mnguenther.com
"""

from __future__ import print_function, division, absolute_import

#::: plotting settings
import seaborn as sns
sns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)
sns.set_style({"xtick.direction": "in","ytick.direction": "in"})
sns.set_context(rc={'lines.markeredgewidth': 1})

#::: modules
import numpy as np
import matplotlib.pyplot as plt

#::: allesfitter modules
from .. import get_mcmc_posterior_samples, get_ns_posterior_samples, get_labels




def mcmc_plot_violins(datadirs, labels, key):
    '''
    Inputs:
    -------
github probml / pyprobml / scripts / linreg_bayes_tfp.py View on Github external
import numpy as np
import seaborn as sns

import tensorflow as tf
from tensorflow.python import tf2
if not tf2.enabled():
  import tensorflow.compat.v2 as tf
  tf.enable_v2_behavior()
  assert tf2.enabled()

import tensorflow_probability as tfp

sns.reset_defaults()
#sns.set_style('whitegrid')
#sns.set_context('talk')
sns.set_context(context='talk',font_scale=0.7)


tfd = tfp.distributions

negloglik = lambda y, rv_y: -rv_y.log_prob(y)


w0 = 0.125
b0 = 5.
x_range = [-20, 60]

def load_dataset(n=150, n_tst=150):
  np.random.seed(43)
  def s(x):
    g = (x - x_range[0]) / (x_range[1] - x_range[0])
    return 3 * (0.25 + g**2.)
github ihansyou / convmhc / src / main.py View on Github external
def generate_informative_img():
    global model
    try:
        allele = request.form.get('target_allele', '')
        pep_seq = request.form.get('target_pepseq', '')
        binder = request.form.get('target_binder', 0, type=int)
        target_img_txt = request.form.get('target_img', '', type=str)
        target_img = json.loads(target_img_txt)
        print 'target_img:', target_img, 'allele', allele, 'pep_seq', pep_seq, 'binder:', binder

        infr_img = model.find_informative_pixels(np.asarray(target_img), binder=binder)
        # plot informative pixels
        p_sites = range(1, 10)
        h_sites = sorted(np.unique([css[1] for css in model.bdomain.contact_sites(9)]) + 1)

        sns.set_context('paper', font_scale=1.1)
        sns.axes_style('white')
        fig, axes = plt.subplots(nrows=1, ncols=1)
        fig.set_figwidth(6)
        fig.set_figheight(2)
        plt.tight_layout()
        fig.subplots_adjust(bottom=0.22)

        g = sns.heatmap(infr_img, ax=axes, annot=False, linewidths=.4, cbar=False)
        # g.set(title='Informative pixels for %s-%s' % (pep_seq, allele))
        g.set_xticklabels(h_sites, rotation=90)
        g.set_yticklabels(p_sites[::-1])
        g.set(xlabel='HLA contact site', ylabel='Peptide position')

        canvas = FigureCanvas(fig)
        output = StringIO.StringIO()
        canvas.print_png(output)
github stanford-futuredata / macrobase / tools / py_analysis / demo_violine.py View on Github external
import pandas as pd
import numpy as np
import argparse
import seaborn as sns
import matplotlib.pyplot as plt


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--csv', required=True)
  parser.add_argument('--context', default='poster',
                      help='Modifies size of legend, axis, etc.')
  args = parser.parse_args()
  df = pd.read_csv(args.csv)
  dff = df.replace([-np.inf, np.inf], np.nan).dropna(subset=['log10_interval_seconds'])
  sns.set_context(args.context)
  plt.figure(figsize=(20, 15))
  sns.violinplot(y='log10_interval_seconds', x='transition', data=dff)
  plt.savefig('violin_log10_interval_seconds.png', dpi=320)
  print('saved figure to violin_log10_interval_seconds.png')
github slinderman / recurrent-slds / rslds / plotting.py View on Github external
"dusty purple",
               "orange",
               "clay",
               "pink",
               "greyish",
               "mint",
               "light cyan",
               "steel blue",
               "forest green",
               "pastel purple",
               "salmon",
               "dark brown"]

colors = sns.xkcd_palette(color_names)
sns.set_style("white")
sns.set_context("paper")


def gradient_cmap(gcolors, nsteps=256, bounds=None):
    """
    Make a colormap that interpolates between a set of colors
    """
    ncolors = len(gcolors)
    if bounds is None:
        bounds = np.linspace(0, 1, ncolors)

    reds = []
    greens = []
    blues = []
    alphas = []
    for b, c in zip(bounds, gcolors):
        reds.append((b, c[0], c[0]))
github mehrdadbakhtiari / adVNTR / advntr / plot.py View on Github external
def plot_pattern_clustering_result():
    import matplotlib.pyplot as plt

    import seaborn as sns
    sns.set()
    sns.set_style("whitegrid")
    sns.set_context("talk")

    from advntr.models import load_unique_vntrs_data
    vntrs = load_unique_vntrs_data('/home/mehrdad/workspace/adVNTR/vntr_data/hg38_selected_VNTRs_Illumina.db')
    from advntr.pattern_clustering import get_pattern_clusters
    patterns_dist = []
    hist_data = {}
    for i, vntr in enumerate(vntrs):
        if vntr.annotation == 'Intron':
            continue
        num_of_clusters = len(get_pattern_clusters(vntr.get_repeat_segments()))
        patterns_dist.append(num_of_clusters)
        if vntr.annotation not in hist_data.keys():
            hist_data[vntr.annotation] = []
        hist_data[vntr.annotation].append(num_of_clusters)
        print(i)
github nespinoza / juliet / juliet.py View on Github external
###############################################################
    ###############################################################


    ###############################################################
    ###############################################################
    ########### FOURTH PLOT: PHOTOMETRY BY PLANET  ################
    ########### ALSO, SAVE PHOTOMETRY BY PLANET    ################
    ###############################################################

    # Phased transits of each planet for each instrument on different plots:
    for nplanet in range(n_transit):
      iplanet = numbering_transit[nplanet]
      for instrument in inames_lc:
        fig, axs = plt.subplots(2, 1,gridspec_kw = {'height_ratios':[3,1]}, figsize=(9,7))
        sns.set_context("talk")
        sns.set_style("ticks")
        matplotlib.rcParams['mathtext.fontset'] = 'stix'
        matplotlib.rcParams['font.family'] = 'STIXGeneral'
        matplotlib.rcParams['font.size'] = '5'
        matplotlib.rcParams['axes.linewidth'] = 1.2
        matplotlib.rcParams['xtick.direction'] = 'out'
        matplotlib.rcParams['ytick.direction'] = 'out'
        matplotlib.rcParams['lines.markeredgewidth'] = 1

        # First, get phases for the current planetary model. For this get median period and t0:
        P,t0 = np.median(out['posterior_samples']['P_p'+str(iplanet)]),np.median(out['posterior_samples']['t0_p'+str(iplanet)])

        # Get the actual phases:
        phases = utils.get_phases(t_lc[instrument_indexes_lc[instrument]],P,t0)

        # Now, as in the previous plot, sample models from the posterior parameters along the phases of interest.