def mfiAdjMeanFigureMaker(measAll, axarr): # Mark IgGs as human measAll['Ig'] = measAll['Ig'].apply(iggRename) fcIter = zip(axarr, FcgRlist) col = sns.crayon_palette(colors=['Tickle Me Pink', 'Brown']) # Loop through receptors creating plot for axx, fcr in fcIter: sns.barplot(x="Ig", y="Meas", hue="TNP", data=measAll.loc[measAll['FcgR'] == fcr, :], ax=axx, ci=68) axx.set_ylabel("Normalized MFI") axx.set_xlabel("") axx.legend_.remove() axx.set_title(texRename(fcr)) axx.set_xticklabels(axx.get_xticklabels(), rotation=40, rotation_mode="anchor", ha="right") # Change colors to make them different that in FcgRidx for ii, child in enumerate(axx.get_children()[0:8]): if ii < 4: child.set_facecolor(col[0]) child.set_edgecolor(col[0]) else: child.set_facecolor(col[1]) child.set_edgecolor(col[1]) axarr[2].legend(bbox_to_anchor=(1.6, 1), loc=2)
def plot_burn_accuracy_by_burn_age(model, dataset, class_labels, scale='days'): try: assert scale in ['days', 'months', 'years'] except AssertionError as E: raise ValueError( f'scale must be one of days, months, or years. Got {scale}') from E num_classes = len(class_labels) results = dated_burn_accuracy(model, dataset, num_classes, scale) df = pd.DataFrame.from_dict(results) df.index = class_labels df /= df.sum() df = df.melt(ignore_index=False).reset_index() age_label = f'Burn Age ({scale.capitalize()})' df.columns = ['Predicted Class', age_label, '% Burns Predicted'] sns.set_theme() palette = sns.crayon_palette(['Forest Green', 'Navy Blue', 'Red']) hue_order = ['Land', 'Water', 'Burn'] df = df[df['Predicted Class'].isin(hue_order)] sns.lmplot(x=age_label, y='% Burns Predicted', hue='Predicted Class', data=df, palette=palette, hue_order=hue_order, height=4, aspect=1.75)
def InVivoPredictComponents(ax): """ Plot model components. """ from .FigureCommon import alternatingRects # Run the in vivo regression model tbN = InVivoPredict()[2] # Only keep the effect columns tbN = tbN.filter(like='eff', axis=1) tbN.index = [ x.replace('Fcg', 'mFcγ').replace('ose-/-', 'ose-').replace('IgG', 'mIgG') for x in tbN.index ] tbN.index.name = 'condition' tbN.reset_index(inplace=True) tbN = pd.melt(tbN, id_vars=['condition']) # Remove eff from cell line labels tbN['variable'] = [x.replace('eff', '') for x in tbN.variable] colors = sns.crayon_palette( ["Shamrock", 'Navy Blue', 'Beaver', 'Goldenrod', 'Radical Red']) with colors: sns.factorplot(x="condition", hue="variable", y="value", data=tbN, ax=ax, kind='bar', legend=False) ax.set_ylabel('Weightings') ax.set_xlabel('') ax.set_ylim(0.0, 1.75) ax.legend(loc='best') # Set alternating grey rectangles in the background to allow for better # readability of the bar graph ax.set_xticklabels(ax.get_xticklabels(), rotation=40, rotation_mode="anchor", ha="right", position=(0, 0.05), fontsize=6.5) numRects = len(tbN['condition'].unique()) alternatingRects(xlims=ax.get_xlim(), ylims=ax.get_ylim(), numRects=numRects, ax=ax)
def maxAffinity(ax): """ Show that the A/I ratio is consistent with activity quantity. """ import matplotlib from ..StoneModMouse import StoneModelMouse Kas = np.squeeze(StoneModelMouse().kaMouse[:, 2]) logR = [4.0, 4.5, 4.0, 4.0] L0, gnu = 1.0E-9, 5 baselineAct = StoneN(logR, Kas, getMedianKx(), gnu, L0).getActivity([1, -1, 1, 1]) table = pd.DataFrame(list(product(np.logspace(start=4, stop=9, num=subsplits), [0, 2, 3])), columns=['adjust', 'ridx']) colors = sns.crayon_palette(['Brick Red', 'Forest Green', 'Brown']) def appFunc(x): KaCur = Kas.copy() KaCur[int(x.ridx)] = x.adjust x['activity'] = StoneN(logR, KaCur, getMedianKx(), gnu, L0).getActivity([1, -1, 1, 1]) # Make ridx == 0 visible if x['ridx'] == 0: x['activity'] += 50 return x table = table.apply(appFunc, axis=1) ax.plot(Kas[0], baselineAct + 50, color=colors[0], marker='o') sns.FacetGrid(hue='ridx', data=table, palette=colors).map(ax.plot, 'adjust', 'activity') ax.plot(Kas[2], baselineAct, color=colors[1], marker='o') ax.plot(Kas[3], baselineAct, color=colors[2], marker='o') ax.set_xlabel(r'$K_a$ of Adjusted mFc$\gamma$R') ax.set_ylabel('Activity Index') ax.set_xscale('log') ax.set_xlim(1.0E4, 1.0E9) patchA = matplotlib.patches.Patch(color=colors[0], label=r'mFc$\gamma$RI') patchB = matplotlib.patches.Patch(color=colors[1], label=r'mFc$\gamma$RIII') patchC = matplotlib.patches.Patch(color=colors[2], label=r'mFc$\gamma$RIV') ax.legend(handles=[patchA, patchB, patchC])
def AverageAvidity(ax): """ Produce the average of avidity of binding in the dilute case. """ from ..StoneModel import StoneMod from ..StoneHelper import getMedianKx from itertools import product logRs = np.arange(3, 7, dtype=np.float) L0, gnus = 1.0E-18, 4 Kas = np.logspace(2, 9, 20) table = pd.DataFrame(list(product(logRs, Kas)), columns=['logR', 'Ka']) def avAv(x): outt = StoneMod(x.logR, x.Ka, gnus, getMedianKx() * x.Ka, L0, fullOutput=True) return outt[1] / outt[0] table['AvAv'] = table.apply(avAv, axis=1) col = sns.crayon_palette( ['Tickle Me Pink', 'Orange', 'Forest Green', 'Royal Purple']) sns.FacetGrid(hue='logR', data=table, palette=col).map(ax.plot, 'Ka', 'AvAv') ax.set_xscale('log') ax.set_ylabel('Average Binding Valency') ax.set_xlabel(r'$K_a$') # Create the legend patches legend_patches = [ matplotlib.patches.Patch(color=C, label=L) for C, L in zip( col, [r'$10^{' + str(int(logr)) + '}$' for logr in logRs]) ] # Plot the legend ax.legend(handles=legend_patches, title=r'# Receptors', labelspacing=0.25)
def rand_color_palette(N): col = [] colors = sns.mpl_palette('Set1', 9) for j in range(N): if j == 9: colors = sns.mpl_palette('Set3', 12) elif j == 21: colors = sns.mpl_palette('Set2', 8) elif j == 29: colors = list(sns.crayons.keys()) i = np.random.randint(0, high=len(colors)) if j >= 29: col += [sns.crayon_palette(colors.pop(i))] else: col += [colors.pop(i)] return col
l_purp = '#c364c5' d_purp = '#7851a9' l_green = '#71bc78' d_green = '#17806d' crayons = [l_purp, d_purp, l_green, d_green] crayons_l = [crayons[0], crayons[2]] crayons_d = [crayons[1], crayons[3]] sns.palplot(sns.color_palette(crayons)) genders = [(0.812, 0.20, 0.551), (0.349, 0.416, 1)] genders_l = [(0.961, 0.282, 0.676), (0.482, 0.529, 1)] # In[22]: crayons = sns.crayon_palette(['Fuchsia', 'Fern']) dark_crayons = sns.crayon_palette(['Royal Purple', 'Tropical Rain Forest']) ladies = sns.diverging_palette(280.2, 327.8, s=85, l=50, n=200) dudes = sns.diverging_palette(200, 263.2, s=85, l=50, n=200) #razzmatazz and jazzberry #tropical rain forest and cerulean # In[23]: fig, ax = plt.subplots(1, ncols=2, figsize=(15, 5), sharey=True) g = sns.swarmplot(x="Science_Anxieties_Pre", y="value", hue="Gender", dodge=True, data=df_anx_pre_gender,
import numpy as np import pandas as pd import seaborn as sns from sklearn.decomposition import PCA from sklearn.preprocessing import scale import fancyimpute as fi import matplotlib.pyplot as plt fiu_blue = sns.crayon_palette(['Denim']) sns.set(context='talk', style='ticks') bx_df = pd.read_csv('imp-dense.csv', header=0, index_col=0) bx_df['beh_nback_neut-gt-neg_rt'] = bx_df['beh_nback_neutface_cor_rt'] - bx_df[ 'beh_nback_negface_cor_rt'] bx_df['beh_nback_neut-gt-pos_rt'] = bx_df['beh_nback_neutface_cor_rt'] - bx_df[ 'bn_posface_cor_rt'] bx_df['sst_cor_stop_pct'] = 1 - bx_df['bs_incor_stop_percent_total'] bx_vars = [ 'cash_choice_task', 'sst_cor_stop_pct', 'upps_y_ss_negative_urgency', 'upps_y_ss_lack_of_planning', 'upps_y_ss_sensation_seeking', 'upps_y_ss_positive_urgency', 'upps_y_lack_perseverance', 'bis_y_ss_bis_sum', 'bis_y_ss_bas_rr', 'bis_y_ss_bas_drive', 'bis_y_ss_bas_fs', 'nihtbx_flanker_agecorrected', 'beh_nback_neut-gt-neg_rt', 'beh_nback_neut-gt-pos_rt' ] impute_pls = fi.SoftImpute(verbose=False) complete_bx = impute_pls.fit_transform(bx_df[bx_vars])
params.loc[iq, key, var]["nodes"] = list(sig_nodes) params.dropna(how="all", inplace=True) nodaleff_sig.to_csv( join(sink_dir, "{0}_local_efficiency_iq_sig_all.csv".format(mask)) ) params.to_csv(join(sink_dir, "{0}_local_efficiency_iq_sig-nodes.csv".format(mask))) n_map = int(len(params[params["max nlog(p)"] > 1].index)) + 1 interval = 1 / n_map husl_pal = sns.husl_palette(n_colors=n_map, h=interval) husl_cmap = LinearSegmentedColormap.from_list(husl_pal, husl_pal, N=n_map) sns.palplot(husl_pal) crayons_l = sns.crayon_palette(["Vivid Tangerine", "Cornflower"]) crayons_d = sns.crayon_palette(["Brick Red", "Midnight Blue"]) grays = sns.light_palette("#999999", n_colors=3, reverse=True) f_2 = sns.crayon_palette(["Red Orange", "Vivid Tangerine"]) m_2 = sns.crayon_palette(["Cornflower", "Cerulean"]) # In[58]: empty_nii = nib.load(join(roi_dir, "roi101.nii.gz")) empty_roi = empty_nii.get_fdata() * 0 empty = nib.Nifti1Image(empty_roi, empty_nii.affine) g = plot_glass_brain(empty, colorbar=False, vmin=0.5, vmax=n_col) i = 0 for var in params.index:
import matplotlib import seaborn as sns DATADIR = "../input/abstraction-and-reasoning-challenge" WORKDIR = "../working" TEST_SAVEPATH = "../working/submission.csv" PALETTE = sns.crayon_palette( ("Eggplant,Aquamarine,Jungle Green,Atomic Tangerine,Blue Bell,Wisteria," + "Banana Mania,Blue Violet,Carnation Pink,Cerise" ).split(",")) #list(sns.crayons)[:10]) COLORMAP = matplotlib.colors.ListedColormap(PALETTE) NORM = matplotlib.colors.Normalize(vmin=0, vmax=9)
def create_cmap(name: str = None, palette_type: str = None, as_cmap: bool = True, **kwargs) -> Union[list, plt.Axes]: """Create a colormap or color palette object. Parameters ---------- name Name of the pyrates colormap. If specified, palette_type will be ignored. palette_type Type of the seaborn color palette to use. Only necessary if no name is specified. as_cmap If true, a matplotlib colormap object will be returned. Else a seaborn color palette (list). kwargs Keyword arguments for the wrapped seaborn functions. Returns ------- Union[list, plt.Axes] cmap or seaborn color palette. """ from seaborn import cubehelix_palette, dark_palette, light_palette, diverging_palette, hls_palette, husl_palette, \ color_palette, crayon_palette, xkcd_palette, mpl_palette import matplotlib.colors as mcolors if '/' in name: # create diverging colormap name1, name2 = name.split('/') vmin = kwargs.pop('vmin', 0.) vmax = kwargs.pop('vmax', 1.) if type(vmin) is float: vmin = (vmin, vmin) if type(vmax) is float: vmax = (vmax, vmax) kwargs1 = kwargs.pop(name1, kwargs) kwargs2 = kwargs.pop(name2, kwargs) cmap1 = create_cmap(name1, **kwargs1, as_cmap=True) cmap2 = create_cmap(name2, **kwargs2, as_cmap=True) n = kwargs.pop('n_colors', 10) if type(n) is int: n = (n, n) colors = np.vstack((cmap1(np.linspace(vmin[0], vmax[0], n[0])), cmap2(np.linspace(vmin[1], vmax[1], n[1])[::-1]))) return mcolors.LinearSegmentedColormap.from_list('cmap_diverging', colors) # extract colorrange if as_cmap: vmin = kwargs.pop('vmin', 0.) vmax = kwargs.pop('vmax', 1.) n = kwargs.pop('n_colors', 10) crange = np.linspace(vmin, vmax, n) if vmax-vmin < 1. else None else: crange = None if 'pyrates' in name: # create pyrates colormap if name == 'pyrates_red': cmap = cubehelix_palette(as_cmap=as_cmap, start=-2.0, rot=-0.1, **kwargs) elif name == 'pyrates_green': cmap = cubehelix_palette(as_cmap=as_cmap, start=2.5, rot=-0.1, **kwargs) elif name == 'pyrates_blue': cmap = dark_palette((210, 90, 60), as_cmap=as_cmap, input='husl', **kwargs) elif name == 'pyrates_yellow': cmap = dark_palette((70, 95, 65), as_cmap=as_cmap, input='husl', **kwargs) elif name == 'pyrates_purple': cmap = dark_palette((270, 50, 55), as_cmap=as_cmap, input='husl', **kwargs) else: # create seaborn colormap if palette_type == 'cubehelix': cmap = cubehelix_palette(name, as_cmap=as_cmap, **kwargs) elif palette_type == 'dark': cmap = dark_palette(name, as_cmap=as_cmap, **kwargs) elif palette_type == 'light': cmap = light_palette(name, as_cmap=as_cmap, **kwargs) elif palette_type == 'hls': cmap = hls_palette(name, **kwargs) elif palette_type == 'husl': cmap = husl_palette(name, **kwargs) elif palette_type == 'diverging': cmap = diverging_palette(name, as_cmap=as_cmap, **kwargs) elif palette_type == 'crayon': cmap = crayon_palette(name, **kwargs) elif palette_type == 'xkcd': cmap = xkcd_palette(name, **kwargs) elif palette_type == 'mpl': cmap = mpl_palette(name, **kwargs) else: cmap = color_palette(name, **kwargs) # apply colorrange if crange is not None: cmap = mcolors.LinearSegmentedColormap.from_list(name, cmap(crange)) return cmap
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 2 14:10:59 2021 @author: dieter """ import pandas import seaborn from matplotlib import pyplot colors = ['Sunset Orange', 'Inchworm'] my_colors = seaborn.crayon_palette(colors) seaborn.palplot(my_colors) data = pandas.read_csv( 'https://tinyurl.com/ib5wvbqc') # Data is available in the 'data' folder. data.head() data['Sex'] = 'Female' data['Sex'][data.Gender == 1] = 'Male' seaborn.lmplot( x='ChestDepth', y='Forearm', data=data, ) seaborn.lmplot( x='ChestDepth',
# walk-forward validation on the test data predictions = list() #last_step = y_train[-1] for i in range(len(x_test)): # predict one step forward x = x_test[i, :] x = x.reshape(1, 1, 1) y_predicted = model.predict(x, batch_size=1)[0] # rescale y_predicted = mins + (((y_predicted + 1) * (maxs - mins)) / 2) # reverse diff() y_predicted = y_predicted + last_step last_step = y_predicted # store forecast predictions.append(y_predicted) #prepare plot preds = numpy.asarray([predictions[i][0] for i in range(len(y_test))]) colors = seaborn.crayon_palette(['Inchworm', 'Lavender']) x = ds_true[:, 1] y = ds_true[:, 0] plt.scatter(x, y, label='Real values', color=colors[0], s=8) x1 = ds_true[int(ratio * dataset.shape[0]) + 1:, 1] y1 = preds[:] plt.scatter(x1, y1, label='Predicted values', color=colors[1], s=8) plt.xlabel('Phi') plt.ylabel('Velocity [m/s]') plt.legend() plt.show()