def update_rcParams(): fontlabel_size=12 tick_size=12 matplotlib.rcParams.update( { 'figure.facecolor' : 'white', # #ECECEC 'figure.autolayout' : True, 'figure.dpi' : 100, 'figure.subplot.wspace' : 0.0, 'figure.subplot.hspace' : 0.0, 'lines.markersize' : 1.5, 'axes.prop_cycle' : matplotlib.cycler(color=['#3B3D91', '#DB5E00', 'k']), 'font.family': 'sans-serif', 'font.sans-serif': 'Helvetica', 'font.weight': 200, 'axes.labelsize': fontlabel_size, 'axes.facecolor' : 'white', 'legend.fontsize': fontlabel_size, 'xtick.labelsize': tick_size, 'ytick.labelsize': tick_size, 'text.usetex': False, 'text.fontsize': fontlabel_size, 'xtick.major.size': 7.5, 'ytick.major.size': 7.5, 'xtick.major.width': 1, 'ytick.major.width': 1, 'contour.negative_linestyle': 'solid', 'agg.path.chunksize' : 10000 } )
def set_pretty_plots(use_latex=False, use_pgf=False, use_microtype=True): if use_latex: if use_pgf: register_backend('pdf', FigureCanvasPgf, 'pgf') rcParams['pgf.texsystem'] = 'pdflatex' preamble = [r'\usepackage{siunitx}', r'\usepackage{lmodern}', r'\usepackage{subdepth}', ] if use_microtype: preamble.append( r'\usepackage[protrusion = true, expansion = true]{microtype}' ) rcParams['text.usetex'] = True rcParams['text.latex.preamble'] = preamble rcParams['pgf.preamble'] = preamble rcParams['text.latex.unicode'] = True rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['STIXGeneral'] rcParams['axes.prop_cycle'] = mpl.cycler(color=set3) rcParams['axes.edgecolor'] = almost_black rcParams['axes.labelcolor'] = almost_black rcParams['text.color'] = almost_black rcParams['grid.color'] = almost_black rcParams['legend.scatterpoints'] = 1 rcParams['legend.fancybox'] = True rcParams['legend.frameon'] = False rcParams['legend.framealpha'] = 0.0 rcParams['lines.linewidth'] = 2.0 # rcParams['image.aspect'] = 'equal' # rcParams['image.origin'] = 'lower' rcParams['image.interpolation'] = 'nearest'
def test_cn(): matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['blue', 'r']) assert mcolors.to_hex("C0") == '#0000ff' assert mcolors.to_hex("C1") == '#ff0000' matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['xkcd:blue', 'r']) assert mcolors.to_hex("C0") == '#0343df' assert mcolors.to_hex("C1") == '#ff0000' matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r']) assert mcolors.to_hex("C0") == '#8e4585' # if '8e4585' gets parsed as a float before it gets detected as a hex # colour it will be interpreted as a very large number. # this mustn't happen. assert mcolors.to_rgb("C0")[0] != np.inf
def compat(key, value): if isinstance(value, str) and value[0] == "[" and value[-1] == "]": str_value = value[1:-1] value = [] for item in str_value.split(','): if item.startswith("u'") or item.startswith("u'"): item = item[1:] value.append(item.strip('\'" ')) if mpl_1_5 and key == 'axes.color_cycle': key = 'axes.prop_cycle' value = matplotlib.cycler('color', value) return key, value
def set_color_cycle(cls, name, axes=None): """Set the color cycle for future plot commands. Parameters ---------- name : str One of the color set names, see help(CBQ). axes : Axes, optional If not provided, sets the default color cycle in the rcParams axes section. Otherwise, sets the color cycle for the given axes. """ rc('axes', **{cyc_name: cycler('color', getattr(cls, name))})
def plot_statistic(self, error, statistic='mean'): statistics = pd.read_csv(self.save_dir_statistics+'statistics.csv', header=[0, 1, 2], index_col=[0]) statistics.sortlevel(axis=0, inplace=True, sort_remaining=True) statistics.sortlevel(axis=1, inplace=True, sort_remaining=True) statistics[statistics == np.inf] = np.nan # index for sorting dataframe methods idx = np.argsort(np.argsort(self.methods)) # second argsort do get idx for undoing sorting # change color cycle cmap = pl.get_cmap('jet') colors = cmap(np.linspace(0.1, 0.9, len(self.methods))) fig = pl.figure(figsize=(9, 8)) ax = fig.add_subplot(111) ax.set_prop_cycle(cycler('color', colors)) for method in self.methods: if statistic == 'min': statistic_min = statistics.loc[(slice(None)), (slice(None), error, statistic)] ax.plot(statistics.index, statistic_min[method], label=method) table(ax, statistic_min[idx].transpose().apply(lambda x: x.map(lambda y: "%.6f" % y)), rowLabels=self.methods, loc='bottom', bbox=[0, -0.7, 1, 0.55]) elif statistic == 'mean': statistic_mean = statistics.loc[(slice(None)), (slice(None), error, statistic)] statistic_std = np.sqrt(statistics.loc[(slice(None)), (slice(None), error, 'var')]) base_line, = ax.plot(statistics.index, statistic_mean[method], label=method) ax.fill_between(statistics.index.values, (statistic_mean[method].values - statistic_std[method].values).flatten(), (statistic_mean[method].values + statistic_std[method].values).flatten(), facecolor=base_line.get_color(), alpha=0.1) table(ax, statistic_mean[idx].transpose().apply(lambda x: x.map(lambda y: "%.6f" % y)), rowLabels=self.methods, loc='bottom', bbox=[0, -0.7, 1, 0.55]) pl.tight_layout(rect=[0.15, 0.36, 1.0, 1.0]) ax.set_xticks(statistics.index) ax.set_xticklabels(statistics.index) pl.legend(fontsize=12) pl.ylim([0, None]) pl.xlabel(statistics.index.name) pl.ylabel(statistic + ' ' + error) pl.savefig(self.save_dir_statistics+'/plot_'+error+'_'+statistic+'.png') pl.show()
def latex_figs(): matplotlib.rcParams['lines.color'] = 'black' matplotlib.rcParams['patch.edgecolor'] = 'black' matplotlib.rcParams['text.color'] = 'black' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['axes.edgecolor'] = 'black' matplotlib.rcParams['axes.labelcolor'] = 'black' matplotlib.rcParams['xtick.color'] = 'black' matplotlib.rcParams['ytick.color'] = 'black' matplotlib.rcParams['grid.color'] = 'black' matplotlib.rcParams['figure.facecolor'] = 'white' matplotlib.rcParams['figure.edgecolor'] = 'white' matplotlib.rcParams['savefig.facecolor'] = 'white' matplotlib.rcParams['savefig.edgecolor'] = 'white' cols = (brewer2mpl.get_map('Set1', 'qualitative', 7)).mpl_colors cols.insert(0,(0.,0.,0.)) matplotlib.rcParams['axes.prop_cycle'] = matplotlib.cycler('color', cols) matplotlib.rcParams['font.size'] = 8 matplotlib.rcParams['lines.linewidth'] = 1.0 matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['text.usetex'] = True
def mismatchplot(positions, counts, filename, fig_kw): cmap = mpl.cm.get_cmap(name='Set1') colors = [cmap(i) for i in np.linspace(0, 1, 12)] mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=colors) fig, axes = plt.subplots( nrows=1, subplot_kw={legend_bg_color_kw: 'white'}, **fig_kw) ref_alt = [] for ref in ['C', 'G', 'A', 'T']: for alt in set(['C', 'G', 'A', 'T']) - set([ref]): axes.plot(positions, [ counts[ref][pos][alt] / sum(counts[ref][pos].values()) for pos in positions ]) ref_alt.append('>'.join([ref, alt])) # Shink current axis by 20% box = axes.get_position() axes.set_position([box.x0, box.y0, box.width, box.height]) axes.yaxis.grid( b=True, which='major', **{ 'color': 'gray', 'linestyle': ':' }) axes.set_axisbelow(True) axes.set_title('Reference mismatches by cycle') axes.set_xlabel('Cycle') axes.set_ylabel('Fraction of mismatches') legend = axes.legend( ref_alt, ncol=int(len(ref_alt) / 3), bbox_to_anchor=(0.5, 0.25), loc='best', prop={ 'size': 8 }) frame = legend.get_frame() frame.set_facecolor('white') for label in legend.get_texts(): label.set_color('black') add_figure_to_archive(fig, filename, 'cycle_specific_base_mismatches.png')
import pandas as pd import palettable as pbl import h5py cmap7 = pbl.colorbrewer.get_map('Set1', 'Qualitative', 7) cmap11 = pbl.colorbrewer.get_map('Paired', 'Qualitative', 12) c11s = cmap11.hex_colors c11s = c11s[1::2] + c11s[::2] # unpair them mpl.rc('image', cmap='viridis', interpolation='nearest') mpl.rc('font', family='STIXGeneral') mpl.rc('legend', fancybox=False, numpoints=1, markerscale=1.5, borderaxespad=0.5, fontsize=16) mpl.rc('figure', figsize=(8,8)) mpl.rc('axes', linewidth=1.5, edgecolor='k', labelsize=22, grid=False, axisbelow=True, prop_cycle= mpl.cycler(color=c11s)) mpl.rc('grid', linewidth=1) mpl.rc('ytick.major', size=5, width=1.5, pad=8) mpl.rc('xtick.major', size=5, width=1.5, pad=8) mpl.rc('xtick', labelsize=18) mpl.rc('ytick', labelsize=18) mpl.rc('lines', linewidth=2) def get_pos_finite(arr): a = arr[np.isfinite(arr)] return a[a>0] ############################################################## working_dir = "/Users/thanasi/ipynb/classes/Nanophotonics (18.369)/FinalProject/waveguide/out/" os.chdir(working_dir)
Jupyter Book will also embed your code blocks and output in your book. For example, here's some sample Matplotlib code: from matplotlib import rcParams, cycler import matplotlib.pyplot as plt import numpy as np plt.ion() # Fixing random state for reproducibility np.random.seed(19680801) N = 10 data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] data = np.array(data).T cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) from matplotlib.lines import Line2D custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4), Line2D([0], [0], color=cmap(.5), lw=4), Line2D([0], [0], color=cmap(1.), lw=4)] fig, ax = plt.subplots(figsize=(10, 5)) lines = ax.plot(data) ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']); There is a lot more that you can do with outputs (such as including interactive outputs) with your book. For more information about this, see [the Jupyter Book documentation](https://jupyterbook.org).
def colour_style(use_style=True): """ Returns *Colour* plotting style. Parameters ---------- use_style : bool, optional Whether to use the style and load it into *Matplotlib*. Returns ------- dict *Colour* style. """ constants = COLOUR_STYLE_CONSTANTS style = { # Figure Size Settings 'figure.figsize': (12.80, 7.20), 'figure.dpi': 100, 'savefig.dpi': 100, 'savefig.bbox': 'standard', # Font Settings # 'font.size': 12, 'axes.titlesize': 'x-large', 'axes.labelsize': 'larger', 'legend.fontsize': 'small', 'xtick.labelsize': 'medium', 'ytick.labelsize': 'medium', # Text Settings 'text.color': constants.colour.darkest, # Tick Settings 'xtick.top': False, 'xtick.bottom': True, 'ytick.right': False, 'ytick.left': True, 'xtick.minor.visible': True, 'ytick.minor.visible': True, 'xtick.direction': 'out', 'ytick.direction': 'out', 'xtick.major.size': constants.geometry.long * 1.25, 'xtick.minor.size': constants.geometry.long * 0.75, 'ytick.major.size': constants.geometry.long * 1.25, 'ytick.minor.size': constants.geometry.long * 0.75, 'xtick.major.width': constants.geometry.short, 'xtick.minor.width': constants.geometry.short, 'ytick.major.width': constants.geometry.short, 'ytick.minor.width': constants.geometry.short, # Spine Settings 'axes.linewidth': constants.geometry.short, 'axes.edgecolor': constants.colour.dark, # Title Settings 'axes.titlepad': plt.rcParams['font.size'] * 0.75, # Axes Settings 'axes.facecolor': constants.colour.brightest, 'axes.grid': True, 'axes.grid.which': 'major', 'axes.grid.axis': 'both', # Grid Settings 'axes.axisbelow': True, 'grid.linewidth': constants.geometry.short * 0.5, 'grid.linestyle': '--', 'grid.color': constants.colour.light, # Legend 'legend.frameon': True, 'legend.framealpha': constants.opacity.high, 'legend.fancybox': False, 'legend.facecolor': constants.colour.brighter, 'legend.borderpad': constants.geometry.short * 0.5, # Lines 'lines.linewidth': constants.geometry.short, 'lines.markersize': constants.geometry.short * 3, 'lines.markeredgewidth': constants.geometry.short * 0.75, # Cycle 'axes.prop_cycle': matplotlib.cycler(color=constants.colour.cycle), } if use_style: plt.rcParams.update(style) return style
'xtick.labelsize': 16, 'ytick.labelsize': 16, }) if mpl_version < '2.0': DEFAULT_PARAMS['font.serif'] = ['Computer Modern'] # build better default colour cycle for matplotlib < 2 if mpl_version < '2.0': try: from matplotlib import cycler except (ImportError, KeyError): # mpl < 1.5 DEFAULT_PARAMS['axes.color_cycle'] = DEFAULT_COLORS else: # mpl >= 1.5 DEFAULT_PARAMS.update({ 'axes.prop_cycle': cycler('color', DEFAULT_COLORS), }) # update matplotlib rcParams with new settings rcParams.update(DEFAULT_PARAMS) # -- dynamic subplot positioning ---------------------------------------------- SUBPLOT_WIDTH = { 6.4: (.1875, .87), 8.: (.15, .85), 12.: (.1, .90), } SUBPLOT_HEIGHT = { 4.: (.2, .85), 4.8: (.16, .88),
'legend.frameon': False, 'pdf.fonttype': 42, 'ps.fonttype': 42, 'mathtext.fontset': 'custom', 'font.size': fontsize, 'font.family' : 'serif', #'font.serif' : 'Source Serif Pro', 'text.usetex': True, 'savefig.bbox':'tight', 'axes.facecolor': lighter_grey, 'axes.labelpad': 10.0, 'axes.labelsize': fontsize * 0.8, 'axes.titlepad': 30, 'axes.titlesize': fontsize, 'axes.grid': False, #'grid.color': white, 'lines.markersize': 7.0, 'lines.scale_dashes': False, 'xtick.labelsize': fontsize * 0.8, 'ytick.labelsize': fontsize * 0.8, 'legend.fontsize': fontsize * 0.8} for k, v in master_formatting.items(): rcParams[k] = v color_cycle = tableau.values() try: from matplotlib import cycler rcParams['axes.prop_cycle'] = cycler(color=color_cycle) except Exception: raise
def adaptermerplot(positions, counts, adapters, filename, fig_kw): all_kmers = [counts[k].keys() for k in sorted(counts.keys())] kmers = tuple( set(list( itertools.chain.from_iterable(all_kmers))).intersection(adapters)) kmer_len = len(tuple(kmers)[0]) kmer_sums = Counter( dict( zip(kmers, [ sum([counts[pos].get(kmer, 0) for pos in positions]) for kmer in kmers ]))) top_kmers = [x[0] for x in kmer_sums.most_common(9)] cmap = mpl.cm.get_cmap(name='Set1') colors = [cmap(i) for i in np.linspace(0, 1, len(top_kmers))] mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=colors) fig, axes = plt.subplots( nrows=1, subplot_kw={legend_bg_color_kw: 'white'}, **fig_kw) kmer_percent = defaultdict(lambda: defaultdict(int)) for pos, count in tuple(counts.items()): for kmer in kmers: pos_count = sum(counts[pos].values()) if pos_count > 0: kmer_percent[pos][kmer] = float(count.get(kmer, 0)) / pos_count * 100 else: kmer_percent[pos][kmer] = 0. for kmer in [x for x in kmers if x not in top_kmers]: axes.plot( positions, [kmer_percent[pos][kmer] for pos in positions], color='0.4', linestyle='dotted') legend_handles = [] for kmer in top_kmers: legend_handles.append( axes.plot(positions, [kmer_percent[pos][kmer] for pos in positions])[0]) # Shink current axis by 20% box = axes.get_position() axes.set_position([box.x0, box.y0, box.width * 0.9, box.height]) axes.yaxis.grid( b=True, which='major', **{ 'color': 'gray', 'linestyle': ':' }) axes.set_axisbelow(True) axes.set_title('Adapter kmer ({0:n}) content'.format(kmer_len)) axes.set_xlabel('Cycle') axes.set_ylabel('Adapter kmer content (% kmer)') legend = axes.legend( legend_handles, top_kmers, ncol=1, bbox_to_anchor=(1, 0.5), loc='center left', prop={ 'size': 8 }) frame = legend.get_frame() frame.set_facecolor('white') for label in legend.get_texts(): label.set_color('black') add_figure_to_archive(fig, filename, 'cycle_specific_potiential_adapter_kmers.png')
import matplotlib as mpl import matplotlib.pylab as pl # some setup for visualizing from brewer2mpl import get_map cols = get_map('RdGy','Diverging',9).mpl_colors col1 = cols[0] col2 = cols[1] col3 = cols[2] col4 = cols[3] col5 = cols[4] col6 = cols[5] col7 = cols[6] col8 = cols[7] col9 = cols[8] mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=[col1, col6 , col3, col4, col5, col7, col8, col9]) from argumenter import phi, Tstar, M_centralstar, R, nr, r_in, r_yd, dlnHpdlr, alpha,delta, rho_s from konstanter import AU, year, k, mu, sig_h2, sigma_sb, G, Msun from lagrange_ini import n, z, a, ri, rl, ru, rc, drc, r, dr, tcurrent, t, tend, tdelta, mass_s def densitets_funktion(r): """setup densities :input: r the distance to central star from point in the center plane of the disc :return: values for gas and dusts surface and mass densities """ T = 0.05**(1/4)*np.abs(r/R)**(-1/2)*Tstar cs = np.sqrt(k*T/mu) # isothermal speed of sound kepler_frq = np.sqrt( np.abs((G*M_centralstar) / r**3 )) H = cs / kepler_frq
tick.set_color('gray') # control face and edge color of histogram ax.hist(x, edgecolor='r', color='#EEAA66') plt.show() # In[ ]: y = np.random.randn(2000) + 2 plt.hist(y, bins=50) plt.show() # In[ ]: colors = mpl.cycler( 'color', ['EEAA66b1', '3388BBb1', '9988DDb1', 'EECC55b1', '88BB44b1', 'FFBBBBb1']) plt.rc('axes', facecolor='#E6E6E6', edgecolor='none', axisbelow=True, grid=True, prop_cycle=colors) plt.rc('grid', color='w', linestyle='solid') plt.rc('xtick', direction='out', color='k') plt.rc('ytick', direction='out', color='k') plt.rc('xtick.major', size=2, width=4, top=False) plt.rc('ytick.major', size=8, width=2, right=False) plt.rc('patch', edgecolor='r')
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['lines.color'] = 'k' mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k']) x = np.linspace(-9, 9, 400) y = np.linspace(-5, 5, 400) x, y = np.meshgrid(x, y) def axes(): plt.axhline(0, alpha=.1) plt.axvline(0, alpha=.1) def line_gen(A, B): len = 2 x_AB = np.zeros((2, len)) lam_1 = np.linspace(-1, 1, len) for i in range(len): temp1 = A + lam_1[i] * (B - A) x_AB[:, i] = temp1.T return x_AB a1 = np.array([5, 0]) b1 = np.array([0, 4]) a2 = np.array([-5, 0]) b2 = np.array([0, -4])
from sklearn import metrics import seaborn as sns from concurrent.futures import ProcessPoolExecutor from itertools import chain flatten = lambda l: list(chain.from_iterable(l)) import multiprocessing max_cpu = multiprocessing.cpu_count() from matplotlib import cycler nice_colors = [ '#EE6666', '#3388BB', '#9988DD', '#EECC55', '#88BB44', '#FFBBBB' ] colors_nice = cycler('color', nice_colors) colors_datasets = sns.color_palette('deep') plt.rc('axes', facecolor='#E6E6E6', edgecolor='none', axisbelow=True, grid=True, prop_cycle=colors_nice) plt.rc('grid', color='w', linestyle='solid') plt.rc('xtick', direction='out', color='black') plt.rc('ytick', direction='out', color='black') plt.rc('patch', edgecolor='#E6E6E6') plt.rc('lines', linewidth=2) mpl.rcParams['figure.figsize'] = [7.0, 5.0]
def set_style(fontsize=12): size = fontsize fontProperties = {'family':'sans-serif','sans-serif':['Helvetica'], 'weight' : 'normal', 'size' : fontsize} # fontProperties = {'family':'sans-serif','sans-serif':['Arial'], # 'weight' : 'normal', 'size' : fontsize} rc('font', **fontProperties) rc('text', usetex=False) mpl.rcParams['mathtext.rm'] = 'Computer Modern' mpl.rcParams['mathtext.it'] = 'Computer Modern:italic' mpl.rcParams['mathtext.bf'] = 'Computer Modern:bold' plt.rc('xtick', color='k', labelsize='large', direction='in') plt.rc('ytick', color='k', labelsize='large', direction='in') plt.rc('xtick.major', size=6, pad=6) plt.rc('xtick.minor', size=4, pad=6) plt.rc('ytick.major', size=6, pad=6) plt.rc('ytick.minor', size=4, pad=6) #rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) # plt.rcParams['text.latex.preamble'] = [ # ## r'\usepackage{time}', # r'\usepackage{tgheros}', # helvetica font # r'\usepackage[]{amsmath}', # math-font matching helvetica # r'\usepackage{bm}', # # r'\sansmath' # actually tell tex to use it! # r'\usepackage{siunitx}', # micro symbols # r'\sisetup{detect-all}', # force siunitx to use the fonts # ] #rc('text.latex', preamble=r'\usepackage{cmbright}') plt.rc('axes', titlesize=size) # fontsize of the axes title plt.rc('axes', labelsize=size) # fontsize of the x any y labels # plt.rc('xtick', labelsize=size) # fontsize of the tick labels # plt.rc('ytick', labelsize=size) # fontsize of the tick labels plt.rc('legend', fontsize=size) # legend fontsize plt.rc('figure', titlesize=size) # # size of the figure title plt.rc('axes', linewidth=1) #plt.rcParams['axes.labelweight'] = 'normal' plt.locator_params(axis='y') # the axes attributes need to be set before the call to subplot #plt.rc('xtick.major', size=4, pad=4) #plt.rc('xtick.minor', size=3, pad=4) #plt.rc('ytick.major', size=4, pad=4) #plt.rc('ytick.minor', size=3, pad=4) plt.rc('savefig',dpi=120) plt.legend(frameon=False) # matlab rgb line colors linecolors = [ (0, 0.4470, 0.7410), (0.8500, 0.3250, 0.0980), (0.9290, 0.6940, 0.1250), (0.4940, 0.1840, 0.5560), (0.4660, 0.6740, 0.1880), (0.3010, 0.7450, 0.9330), (0.6350, 0.0780, 0.1840)] plt.rcParams['axes.prop_cycle'] = mpl.cycler(color=linecolors) #plt.rcParams["xtick.minor.visible"] = True # using aliases for color, linestyle and linewidth; gray, solid, thick #plt.rc('grid', c='0.5', ls='-', lw=5) plt.rc('lines', lw=2) return
from matplotlib import cycler from plottr.plot.pyqtgraph.autoplot import AutoPlot as PGAutoPlot from plottr.plot.mpl.autoplot import AutoPlot as MPLAutoPlot config = { 'default-plotwidget': MPLAutoPlot, 'matplotlibrc': { 'axes.grid': True, 'axes.prop_cycle': cycler('color', [ '1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf' ]), 'figure.dpi': 150, 'figure.figsize': (4.5, 3), 'font.size': 6, 'font.family': ['Helvetica', 'Arial', 'DejaVu Sans', 'Bitstream Vera Sans'], 'grid.linewidth': 0.5, 'grid.linestyle': '--', 'image.cmap': 'magma', 'legend.fontsize': 6, 'legend.frameon': True,
import numpy as np import numpy.polynomial.polynomial as poly import matplotlib as mpl import matplotlib.pyplot as plt import array import datetime import scipy.signal as scp from matplotlib import rc from matplotlib.ticker import ScalarFormatter from matplotlib.ticker import FormatStrFormatter CB_color_cycle = [ '#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00' ] mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=CB_color_cycle) rc('text', usetex=True) rc('text.latex', preamble=r'\usepackage{gensymb}') #!python numbers=disable fig_width_pt = 426.0 # Get this from LaTeX using \showthe\columnwidth result: inches_per_pt = 1.0 / 72.27 # Convert pt to inches golden_mean = (np.sqrt(5) - 1.0) / 2.0 # Aesthetic ratio fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * golden_mean # height in inches fig_size = [fig_width, fig_height] params = { 'backend': 'ps', 'axes.labelsize': 10, 'font.size': 10,
def set_mpl_defaults(matplotlib): """This function updates the matplotlib library to adjust some default plot parameters Args: matplotlib : matplotlib instance Returns: matplotlib instance """ params = { "font.size": 6, "axes.labelsize": 6, "axes.titlesize": 6, "xtick.labelsize": 6, "ytick.labelsize": 6, "figure.titlesize": 6, "legend.fancybox": True, "legend.fontsize": 6, "legend.handletextpad": 0.25, "legend.handlelength": 1, "legend.labelspacing": 0.7, "legend.columnspacing": 1.5, "legend.edgecolor": (0, 0, 0, 1), # solid black "patch.linewidth": 0.75, "figure.dpi": 300, "figure.figsize": (2, 2), "lines.linewidth": 0.75, "lines.markeredgewidth": 1, "lines.markeredgecolor": "black", "lines.markersize": 2, "axes.linewidth": 0.75, # "axes.spines.right": False, # "axes.spines.top": False, "axes.prop_cycle": cycler( "color", [ "slategray", "darksalmon", "mediumaquamarine", "indianred", "orchid", "paleturquoise", "tan", "lightpink", ], ), } # Update parameters matplotlib.rcParams.update(params) return matplotlib
import matplotlib.pyplot as plt import matplotlib as mpl from pathlib import Path from utils import show_flag plt.style.use('seaborn') mpl.rcParams['axes.prop_cycle'] = mpl.cycler( color=['#22848e', '#f88904', '#78c18c']) mpl.rcParams['savefig.transparent'] = True mpl.rcParams['lines.linewidth'] = 2.5 mpl.rcParams['lines.markersize'] = 6 mpl.rcParams['font.family'] = 'Montserrat' weight = 'semibold' mpl.rcParams['font.weight'] = weight mpl.rcParams['axes.titleweight'] = weight mpl.rcParams['axes.labelweight'] = weight mpl.rcParams['figure.titleweight'] = weight gray = '#e2e2e2' mpl.rcParams['axes.labelcolor'] = gray mpl.rcParams['axes.edgecolor'] = gray mpl.rcParams['text.color'] = gray brighter = '#6a624a' mpl.rcParams['xtick.color'] = brighter mpl.rcParams['ytick.color'] = brighter mpl.rcParams['grid.color'] = brighter bgcolor = '#343025' # mpl.rcParams['boxplot.patchartist'] = True
# calc_variance_for_each_pixel.py # Tomomasa Uchida # 2019/05/04 import numpy as np from matplotlib import pyplot as plt from matplotlib import cycler import matplotlib.gridspec as gridspec import matplotlib.patches as pat import cv2 import statistics # Graph settings plt.style.use('seaborn-white') colors = cycler('color', ['#EE6666', '#3388BB', '#9988DD', '#EECC55', '#88BB44', '#FFBBBB']) plt.rc('axes', facecolor='#E6E6E6', edgecolor='none', axisbelow=True, grid=False, prop_cycle=colors) plt.rc('grid', color='w', linestyle='solid') plt.rc('patch', edgecolor='#E6E6E6') plt.rc('lines', linewidth=2) plt.rcParams["mathtext.fontset"] = "stix" plt.rcParams["mathtext.rm"] = "Times New Roman" # Check arguments import sys args = sys.argv if len(args) != 5: print("\nUSAGE : $ python calc_variance_for_each_pixel.py [input_images_path] [output_path] [repeat_level] [image_resolution]") print("EXAMPLE : $ python calc_variance_for_each_pixel.py OUTPUT/LR100/IMAGE_DATA/ OUTPUT/LR100/ 100 1000\n") sys.exit()
def change_plot(self, plot_data_collection): """Plot all data from the *plot_data_collection* :param plot_data_collection: A iterable collection of :clas: `PlotData` objects, which should be plotted. temporal data """ if len(plot_data_collection) == 0: return if len(plot_data_collection) > 10: msg = QMessageBox(self) msg.setIcon(QMessageBox.Information) msg.setText( "Your selection intends to plot more that 10 curves, do you really want to continue?" ) msg.setWindowTitle("Info") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) result = msg.exec() if result == QMessageBox.Cancel: return self.ax.clear() self.ax.grid(True) self.ax.set_prop_cycle( cycler('color', [ 'r', 'b', 'y', 'k', 'c', 'm', 'g', 'r', 'b', 'y', 'k', 'c', 'm', 'g' ]) + cycler('marker', [ 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'o', 'o', 'o', 'o', 'o', 'o', 'o' ])) self.ax.set_xlabel(plot_data_collection[0].label[0]) self.ax.set_ylabel(plot_data_collection[0].label[1]) # Now lets create a legend only containing informative # content (no duplicates) tmp_legend = [] for plot_data in plot_data_collection: tmp = [] for identifiers in plot_data.identifiers: tmp += identifiers.split(sep) tmp2 = tmp + plot_data.path tmp_legend.append(tmp2) legend = [] for c in tmp_legend: result = list( filter(lambda x: all(x in l for l in tmp_legend) == False, c)) legend.append(" ".join(result)) if len(tmp_legend) == 1: legend = [''] # plot all the lines which are missing yet plot_count = 0 for plot_data in plot_data_collection: # Create legend from variable path and sim data items identifiers l = legend[ plot_count] #" ".join([i for i in plot_data.identifiers] + plot_data.path) # Convert list of pairs of strings to two sorted lists of floats values = ((float(x), float(y)) for (x, y) in plot_data.values) sorted_value_pairs = sorted(values, key=lambda pair: pair[0]) [xs, ys] = list(zip(*sorted_value_pairs)) # plot the current plotdata and set the legend curve = self.ax.plot(xs, ys, label=l) plot_count += 1 if not (legend == ['']): self.ax.legend(loc='lower right') DataCursor(self.ax.get_lines()) start, end = self.ax.get_ylim() start = math.floor(start) end = math.ceil(end) if abs(start - end) < 20: self.ax.yaxis.set_ticks(np.arange(start, end, 0.5)) self.plotAreaWidget.canvas.draw()
def nyquist_plot(sys, w=None, use_hz=True, negative_freqs=True, style=None, **kwargs): """Draw the Nyquist plot of State, Transfer model(s). Parameters ---------- sys : {State,Transfer}, iterable The system(s) for which the Bode plot will be drawn. For multiple plots, place the systems inside a list, tuples, etc. Generators will not work as they will be exhausted before the plotting is performed. w : array_like Range of frequencies. For discrete systems the frequencies above the nyquist frequency is ignored. If sys is an iterable w is used for all systems. use_hz : bool, optional Uses Hz unit for the output frequencies. This also assumes the input frequencies are in Hz. negative_freqs : bool Draw or hide the negative frequencies. Default is True style : cycler.Cycler, optional Matplotlib cycler class instance for defining the properties of the plot artists. If not given, the current defaults will be used. If any, all remaining kwargs are passed to `matplotlib.pyplot.subplots()`. Returns ------- plot : matplotlib.figure.Figure """ syslist = _check_sys_args(sys) f_unit = 'Hz' if use_hz else 'rad/s' # Prepare the axes for the largest model max_p, max_m = np.max(np.array([x.shape for x in syslist]), axis=0) # Put some more space between columns to avoid ticklabel placement clashes gridspec_kw = kwargs.pop('gridspec_kw', None) if gridspec_kw is None: gridspec_kw = {'wspace': 0.5} else: wspace = gridspec_kw.get('wspace', 0.5) gridspec_kw['wspace'] = wspace # MIMO plots needs a bit bigger figure, offer a saner default figsize = kwargs.pop('figsize', None) if figsize is None: figsize = (6.0 + 1.2 * (max_m - 1), 4 + 1.5 * (max_p - 1)) # Create fig and axes fig, axs = plt.subplots(max_p, max_m, sharex=True, squeeze=False, gridspec_kw=gridspec_kw, figsize=figsize, **kwargs) if style is None: style = mpl.cycler(mpl.rcParams['axes.prop_cycle']) # If multiple systems are given and no freq grid is given we need to find # the common freq grid. if w is None and len(syslist) > 1: W = _get_common_freq_grid(syslist) for ind, (G, sty) in enumerate(zip(syslist, style)): # If multiple systems are given W is necessarily defined here. if w is None and len(syslist) > 1: w = W[ind] if f_unit == 'Hz': w /= 2 * np.pi if w is not None: fre, ww = frequency_response(G, w, w_unit=f_unit, output_unit=f_unit) else: fre, ww = frequency_response(G, output_unit=f_unit) rr = fre.real ii = fre.imag p, m = G.shape for col in range(m): for row in range(p): # If SISO expand the arrays to 3D if G._isSISO: rdata = rr idata = ii else: rdata = rr[row, col, :] idata = ii[row, col, :] axs[row, col].plot(rdata, idata, '-') axs[row, col].plot(rdata, -idata, '-.') axs[row, col].plot([-1], [0], 'b+') axs[row, col].grid(True, which='both') # MIMO Labels and gridding if col == 0: axs[row, col].set_ylabel('Imaginary Part') if row == p - 1: axs[row, col].set_xlabel('Real Part') return fig
def embedding( adata: AnnData, basis: str, *, color: Union[str, Sequence[str], None] = None, panel_size: Tuple[float, float] = (4, 4), palette: Union[str, Cycler, Sequence[str], Sequence[Cycler], None] = None, legend_loc: str = "right margin", ax: Optional[Union[plt.Axes, Sequence[plt.Axes]]] = None, ncols: int = 3, show: Optional[bool] = False, hspace: float = 0.25, wspace: float = None, **kwargs, ) -> Union[None, Sequence[plt.Axes]]: """A customized wrapper to the :func:`scanpy.pl.embedding` function. The differences to the scanpy embedding function are: * allows to specify a `panel_size` * Allows to specify a different `basis`, `legend_loc` and `palette` for each panel. The number of panels is defined by the `color` parameter. * Use a patched version for adding "on data" labels. The original raises a flood of warnings when coords are `nan`. * For columns with many categories, cycles through colors instead of reverting to grey * allows to specify axes, even if multiple colors are set. Parameters ---------- adata annotated data matrix basis embedding to plot. Get the coordinates from the "X_{basis}" key in `adata.obsm`. This can be a list of the same length as `color` to specify different bases for each panel. color Keys for annotations of observations/cells or variables/genes, e.g., `'ann1'` or `['ann1', 'ann2']`. panel_size Size tuple (`width`, `height`) of a single panel in inches palette Colors to use for plotting categorical annotation groups. The palette can be a valid :class:`~matplotlib.colors.ListedColormap` name (`'Set2'`, `'tab20'`, …) or a :class:`~cycler.Cycler` object. It is possible to specify a list of the same size as `color` to choose a different color map for each panel. legend_loc Location of legend, either `'on data'`, `'right margin'` or a valid keyword for the `loc` parameter of :class:`~matplotlib.legend.Legend`. ax A matplotlib axes object or a list with the same length as `color` thereof. ncols Number of columns for multi-panel plots show If True, show the firgure. If false, return a list of Axes objects wspace Adjust the width of the space between multiple panels. hspace Adjust the height of the space between multiple panels. **kwargs Arguments to pass to :func:`scanpy.pl.embedding`. Returns ------- axes A list of axes objects, containing one element for each `color`, or None if `show == True`. See also -------- :func:`scanpy.pl.embedding` """ adata._sanitize() def _make_iterable(var, singleton_types=(str,)): return ( itertools.repeat(var) if isinstance(var, singleton_types) or var is None else list(var) ) color = [color] if isinstance(color, str) or color is None else list(color) basis = _make_iterable(basis) legend_loc = _make_iterable(legend_loc) palette = _make_iterable(palette, (str, Cycler)) # set-up grid, if no axes are provided if ax is None: n_panels = len(color) nrows = int(np.ceil(float(n_panels) / ncols)) ncols = np.min((n_panels, ncols)) hspace = ( rcParams.get("figure.subplot.hspace", 0.0) if hspace is None else hspace ) wspace = ( rcParams.get("figure.subplot.wspace", 0.0) if wspace is None else wspace ) # Don't ask about +/- 1 but appears to be most faithful to the panel size fig_width = panel_size[0] * ncols + hspace * (ncols + 1) fig_height = panel_size[1] * nrows + wspace * (nrows - 1) fig, axs = plt.subplots( nrows=nrows, ncols=ncols, figsize=(fig_width, fig_height), gridspec_kw={"wspace": wspace, "hspace": hspace}, squeeze=False, ) axs = axs.flatten() else: axs = [ax] if not isinstance(ax, Sequence) else list(ax) fig = axs[0].get_figure() # use the scanpy plotting api to fill individual components for ax, tmp_color, tmp_basis, tmp_legend_loc, tmp_palette in zip( axs, color, basis, legend_loc, palette ): # cycle colors for categories with many values instead of # coloring them in grey if tmp_palette is None and tmp_color is not None: if str(adata.obs[tmp_color].dtype) == "category": if adata.obs[tmp_color].unique().size > len(sc.pl.palettes.default_102): tmp_palette = cycler(color=sc.pl.palettes.default_102) add_labels = tmp_legend_loc == "on data" tmp_legend_loc = None if add_labels else tmp_legend_loc sc.pl.embedding( adata, tmp_basis, ax=ax, show=False, color=tmp_color, legend_loc=tmp_legend_loc, palette=tmp_palette, **kwargs, ) # manually add labels for "on data", as missing entries in `obsm` will cause # a flood of matplotlib warnings. # TODO: this could eventually be fixed upstream in scanpy if add_labels: _add_labels( ax, adata.obsm["X_" + tmp_basis], adata.obs[tmp_color].values, legend_fontweight=kwargs.get("legend_fontweight", "bold"), legend_fontsize=kwargs.get("legend_fontsize", None), legend_fontoutline=kwargs.get("legend_fontoutline", None), ), # hide unused panels in grid for ax in axs[len(color) :]: ax.axis("off") if show: fig.show() else: # only return axes that actually contain a plot. return axs[: len(color)]
def bode_plot(sys, w=None, use_db=False, use_hz=True, use_degree=True, style=None, **kwargs): """Draw the Bode plot of State, Transfer model(s). As the name implies, this only creates a plot. For the actual frequency response data use the `frequency_response()` which is also used internally. Parameters ---------- sys : {State,Transfer}, iterable The system(s) for which the Bode plot will be drawn. For multiple plots, place the systems inside a list, tuples, etc. Generators will not work as they will be exhausted before the plotting is performed. w : array_like Range of frequencies. For discrete systems the frequencies above the nyquist frequency is ignored. If sys is an iterable w is used for all systems. use_db : bool, optional Uses the deciBell unit for the magnitude plots. use_hz : bool, optional Uses Hz unit for the output frequencies. This also assumes the input frequencies are in Hz. use_degree : bool, optional The phase angle is shown in degrees or in radians. style : cycler.Cycler, optional Matplotlib cycler class instance for defining the properties of the plot artists. If not given, the current defaults will be used. If any, all remaining kwargs are passed to `matplotlib.pyplot.subplots()`. Returns ------- plot : matplotlib.figure.Figure Notes ----- Every curve plotted in the Bode plot is labeled with the convention of ``sys_<number>_in_<number>_out_<number>_<mag or phase>`` where numbers are all 0-indexed. The first index is the model number given in the ``sys`` argument, and the other two are only nonzero when MIMO models are used. For discrete models the vertical lines are suffixed with ``_nyqline``. """ syslist = _check_sys_args(sys) f_unit = 'Hz' if use_hz else 'rad/s' db_scale = 20 if use_db else 1 # Prepare the axes for the largest model max_p, max_m = np.max(np.array([x.shape for x in syslist]), axis=0) # Put some more space between columns to avoid ticklabel placement clashes gridspec_kw = kwargs.pop('gridspec_kw', None) if gridspec_kw is None: gridspec_kw = {'wspace': 0.5} else: wspace = gridspec_kw.get('wspace', 0.5) gridspec_kw['wspace'] = wspace # MIMO plots needs a bit bigger figure, offer a saner default figsize = kwargs.pop('figsize', None) if figsize is None: figsize = (6.0 + 1.2 * (max_m - 1), 4 + 1.5 * (max_p - 1)) # Create fig and axes fig, axs = plt.subplots(2 * max_p, max_m, sharex=True, squeeze=False, gridspec_kw=gridspec_kw, figsize=figsize, **kwargs) if style is None: style = mpl.cycler(mpl.rcParams['axes.prop_cycle']) # If multiple systems are given and no freq grid is given we need to find # the common freq grid. if w is None and len(syslist) > 1: W = _get_common_freq_grid(syslist) for ind, (G, sty) in enumerate(zip(syslist, style)): # If multiple systems are given W is necessarily defined here. if w is None and len(syslist) > 1: w = W[ind] if f_unit == 'Hz': w /= 2 * np.pi isDiscrete = True if G.SamplingSet == 'Z' else False if isDiscrete: dt = G.SamplingPeriod nyq = 1 / (2 * dt) if use_hz else np.pi / dt if w is not None: fre, ww = frequency_response(G, w, w_unit=f_unit, output_unit=f_unit) else: fre, ww = frequency_response(G, output_unit=f_unit) fre[np.abs(fre) == 0.] = np.nan mag = db_scale * np.log10(np.abs(fre)) # Mask NaN values if any if np.isnan(fre).any(): pha = np.empty_like(fre, dtype=float) pha[~np.isnan(fre)] = np.unwrap(np.angle(fre[~np.isnan(fre)])) else: pha = np.unwrap(np.angle(fre)) if use_degree: pha = np.rad2deg(pha) p, m = G.shape for col in range(m): for row in range(p): # If SISO expand the arrays to 3D if mag.ndim == 1: mag = mag[None, None, :] pha = pha[None, None, :] label = f'sys_{ind}_in_{col}_out_{row}_mag' axs[2 * row, col].semilogx(ww, mag[row, col, :], label=label, **sty) label = f'sys_{ind}_in_{col}_out_{row}_phase' axs[2 * row + 1, col].semilogx(ww, pha[row, col, :], label=label, **sty) if isDiscrete: label = f'sys_{ind}_in_{col}_out_{row}_mag_nyqline' axs[2 * row, col].axvline(nyq, linestyle='dashed', linewidth=2, label=label, **sty) label = f'sys_{ind}_in_{col}_out_{row}_phase_nyqline' axs[2 * row + 1, col].axvline(nyq, linestyle='dashed', linewidth=2, label=label, **sty) axs[2 * row, col].grid(True, which='both') axs[2 * row + 1, col].grid(True, which='both') # Only set the last item in that column to have x tick labels plt.setp(axs[2 * row + 1, col].get_xticklabels(), visible=True) # Turn off the unused axes through a kind-of-ugly hack. # I can't find any other sane way to do this with current matplotlib if len(syslist) > 1: dummy_array = np.full([2 * max_p, max_m], 0) for (x, y) in [x.shape for x in syslist]: dummy_array[:2 * x, :y] = 1 # Go through every column and move the x tick labels up before # hiding the empty frames - Why is matplotlib so hard? for col in range(max_m): nonempty_frames = np.count_nonzero(dummy_array[:, col]) if nonempty_frames < 2 * max_p: # Get the ticklabels axs[nonempty_frames - 1, col].tick_params(axis='x', labelbottom=True) for row in range(nonempty_frames, 2 * max_p): axs[row, col].set_visible(False) xlabel_text = f'Frequency [{f_unit}]' ylabel_text = 'Magnitude {} and Phase {}'.format( '[dB]' if use_db else r'[$\mathregular{10^x}$]', '[deg]' if use_degree else '[rad]') fig.text(0.5, 0, xlabel_text, ha='center') fig.text(0, 0.5, ylabel_text, va='center', rotation='vertical') fig.align_ylabels() return fig
LIGHT_BLUE_NORD = NORD9 BLUE_NORD = NORD10 RED_NORD = NORD11 ORANGE_NORD = NORD12 YELLOW_NORD = NORD13 GREEN_NORD = NORD14 VIOLET_NORD = NORD15 # Matplotlib parameters mpl.rcParams['grid.alpha'] = '0.4' mpl.rcParams['xtick.labelsize'] = 14 mpl.rcParams['ytick.labelsize'] = 14 mpl.rcParams['figure.figsize'] = [16, 8] color_array = [NORD10, NORD12, NORD14, NORD11, NORD15] mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=color_array) # Useful functions def tag_ax(ax, text, pos='topright'): if isinstance(pos, tuple): ax.text(*pos, text, fontweight='bold', fontsize=16, va='center', ha='center', transform=ax.transAxes, c=BLACK_NORD, bbox={
'ytick.direction': 'in', 'ytick.major.pad': 6.0, 'ytick.major.size': 0.0, 'ytick.minor.pad': 6.0, 'ytick.minor.size': 0.0 } from distutils.version import StrictVersion import matplotlib colors = ['#348ABD', '#7A68A6', '#A60628', '#467821', '#CF4457', '#188487', '#E24A33'] if StrictVersion(matplotlib.__version__) < StrictVersion("1.5.1"): MPL_STYLE['axes.color_cycle'] = colors else: MPL_STYLE['axes.prop_cycle'] = matplotlib.cycler("color", colors) ARGS_TO_FORWARD = [ "marker", "markersize", "markevery", "linestyle", "linewidth", "drawstyle"] """kwargs that will be forwarded to matplotlib API calls """ HTML_HEIGHT = 400 """Default height for HTML based plots""" DEFAULT_SYNC_ZOOM = False """Sync Graph zoom by default in :mod:`trappy.plotter.ILinePlot` graph groups
#%matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl #%config InlineBackend.figure_f.ormats=['svg'] mpl.rc('axes', prop_cycle=(mpl.cycler('color', ['r', 'k', 'b', 'g', 'y', 'm', 'c']))) mpl.rc('xtick', labelsize=12) mpl.rc('ytick', labelsize=12) import numpy as np # Code for simple gene expression without delay # Import relevant types # from bioscrape.types import Model # from bioscrape.simulator import DeterministicSimulator, SSASimulator # from bioscrape.simulator import ModelCSimInterface from libsbml import * import simplesbml import libsbml model = simplesbml.sbmlModel() model.addCompartment(1e-14, comp_id='comp') model.addSpecies('E', 5e-21, comp='comp') model.addSpecies('S', 1e-20, comp='comp') model.addSpecies('P', 0.0, comp='comp') model.addSpecies('ES', 0.0, comp='comp')
from scipy.misc import derivative from scipy.integrate import quad from scipy.optimize import curve_fit, minimize import ROOT as R try: import matplotlib as mpl has_mpl = True import matplotlib.pyplot as pyp rc, rcParams = mpl.rc, mpl.rcParams rcParams['lines.linewidth'] = 2.0 rcParams['lines.markeredgewidth'] = 1.0 rcParams['font.family'] = 'Times New Roman' rcParams['axes.titlesize'] = 'xx-large' rcParams['axes.labelweight'] = 'bold' rcParams['axes.formatter.useoffset'] = False rcParams['axes.prop_cycle'] = mpl.cycler('color', 'brkgmcy') rcParams['xtick.major.size'] = 8 rcParams['xtick.minor.size'] = 4 rcParams['xtick.major.width'] = 1 rcParams['xtick.labelsize'] = 'xx-large' rcParams['ytick.major.size'] = 8 rcParams['ytick.minor.size'] = 4 rcParams['ytick.major.width'] = 1 rcParams['ytick.labelsize'] = 'xx-large' rcParams['legend.fancybox'] = True rcParams['legend.numpoints'] = 1 rcParams['legend.fontsize'] = 'x-large' rcParams['legend.handletextpad'] = 0.5 rcParams['legend.shadow'] = True rcParams['legend.frameon'] = False rcParams['legend.scatterpoints'] = 1
'#BCBCBC', # axes edge color 'axes.linewidth': 1, # edge linewidth 'axes.grid': False, # display grid or not 'axes.titlesize': 'large', # fontsize of the axes title 'axes.labelsize': 'large', # fontsize of the x any y labels 'axes.labelcolor': '#555555', 'axes.axisbelow': True, # whether axis gridlines and ticks are below 'axes.prop_cycle': cycler(color=[ '#348ABD', '#7A68A6', '#A60628', '#467821', '#CF4457', '#188487', '#E24A33' ]), # blue, purple, red, # green, pink, turquoise, # orange 'axes.unicode_minus': True, 'xtick.major.size': 8, # major tick size in points 'xtick.minor.size': 4, # minor tick size in points 'xtick.major.pad': 6, # distance to major tick label in points 'xtick.minor.pad': 6, # distance to the minor tick label in points 'xtick.color':
from pathlib import Path import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.ticker import PercentFormatter color = '#1f77b4' format = 'png' plt.style.use('ggplot') plt.rcParams['font.family'] = 'Times New Roman' mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=[color]) def plot_connection_solver_execution_time_hist( execution_time: pd.Series) -> plt.Figure: fig, ax = plt.subplots(figsize=(6, 4)) sns.histplot(execution_time, binwidth=0.2, kde=True, ax=ax) ax.set(xlabel='Czas wyszukiwania połączeń [s]', ylabel='Procent przetworzonych zapytań') ax.yaxis.set_major_formatter(PercentFormatter(len(execution_time))) return fig def plot_connection_solver_execution_time_ecdf( execution_time: pd.Series) -> plt.Figure: fig, ax = plt.subplots(figsize=(6, 4)) sns.ecdfplot(execution_time, ax=ax)
#-- figure ------- for prtype in lprtype: outDir = '/home/utsumi/mnt/wellshare/GPMGV/dt-lev-%s/dist.%.1fkm.ndom.%02d.%04d.%02d-%04d.%02d'%(prdName, thdist, len(ldomain), iYM[0], iYM[1], eYM[0], eYM[1]) for dattype in ldattype: datPath=outDir + '/dt-lev.base.%s.%s.%s.%s.npy'%(basepr, prdName, dattype, prtype) a2dat = np.load(datPath) fig = plt.figure(figsize=(4,8)) ax = fig.add_axes([0.15, 0.1, 0.8, 0.8]) a1t = range(-offset_bef, offset_aft+1) cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0,1,nh))) cmap = plt.get_cmap('coolwarm') for ih in range(nh): a1y = a2dat[ih,:] a1y = ma.masked_invalid(a1y) if ih==0: ax.plot(a1t, a1y, '--', c='k', zorder=10, label='%d'%(ih)) else: ax.plot(a1t, a1y, '-', c=cmap(float(ih)/nh), label='%d'%(ih)) # legend ax.legend() # ylim if dattype in ['cc']: ymin = 0.0
r'\sisetup{detect-family=true, per-mode=reciprocal}', # r'\usepackage{sfmath}', r'\usepackage{amsmath}', r'\usepackage{nicefrac}', ], 'text.color': '#555555', 'axes.facecolor': '#EEEEEE', # axes background color 'axes.edgecolor': '#BCBCBC', # axes edge color 'axes.linewidth': 1, # edge linewidth 'axes.grid': False, # display grid or not 'axes.titlesize': 'large', # fontsize of the axes title 'axes.labelsize': 'large', # fontsize of the x any y labels 'axes.labelcolor': '#555555', 'axes.axisbelow': True, # whether axis gridlines and ticks are below 'axes.prop_cycle': cycler(color=['#348ABD', '#7A68A6', '#A60628', '#467821', '#CF4457', '#188487', '#E24A33']), # blue, purple, red, # green, pink, turquoise, # orange 'axes.unicode_minus': True, 'xtick.major.size': 8, # major tick size in points 'xtick.minor.size': 4, # minor tick size in points 'xtick.major.pad': 6, # distance to major tick label in points 'xtick.minor.pad': 6, # distance to the minor tick label in points 'xtick.color': '#555555', # color of the tick labels 'xtick.labelsize': fontsize, 'xtick.direction': 'in', # direction: in or out 'ytick.major.size': 8, # major tick size in points 'ytick.minor.size': 4, # minor tick size in points 'ytick.major.pad': 6, # distance to major tick label in points
def line(gwaff): with open("config.yml", "r") as file: config = safe_load(file) mpl.rcParams["axes.prop_cycle"] = mpl.cycler(color=[ "blue", "green", "red", "cyan", "magenta", "yellow", "black", "purple", "pink", "brown", "orange", "teal", "coral", "lightblue", "lime", "lavender", "turquoise", "darkgreen", "tan", "salmon", "gold", ]) if config["darkmode"]: plt.style.use("dark_background") plt.figure(figsize=(14, 7)) g = 0 q = 0 rankrange = [0, config["plot"]["rank_range"]] for user in gwaff: if g < config["plot"]["range"]: if q < config["plot"]["range"] - 1: y = [0] x = [] total_xp = gwaff[user]["total_xp"] for i in zip(list(total_xp), list(total_xp)[1:]): first = i[0] second = i[1] y.append(abs(total_xp[first] - total_xp[second])) if y[-1] < config["plot"]["minium_xp"]: q += 1 g += 1 continue f = 0 while f < len(total_xp): x.append(f) f += 1 plt.plot(x, y, label=gwaff[user]["name"].split("#")[0]) q += 1 g += 1 else: labelLines(plt.gca().get_lines(), align=True) plt.legend(bbox_to_anchor=(1, 1)) plt.xlabel( f"days since {list(gwaff['408355239108935681']['message_count'].keys())[0].split(' ')[0]}{config['bottom_message']}" ) plt.ylabel("gain") title = f"{config['title']}\nrank: {rankrange[0]}-{rankrange[1]}" rankrange[0] = rankrange[1] rankrange[1] = rankrange[1] + config["plot"]["rank_range"] if config["plot"]["minium_xp"] > 0: title += f"\ngain atleast {config['plot']['minium_xp']} to appear" plt.title(f"{title}\nxp gained overtime") plt.show() plt.close() plt.figure(figsize=(14, 7)) q = 0 else: break
def set_color_cycles(colors): if mpl_1_5: matplotlib.rcParams["axes.prop_cycle"] = matplotlib.cycler('color', colors) else: matplotlib.rcParams["axes.color_cycle"] = colors
"ytick.color": "#555555", "ytick.direction": "in", "ytick.major.pad": 6.0, "ytick.major.size": 0.0, "ytick.minor.pad": 6.0, "ytick.minor.size": 0.0, } from distutils.version import LooseVersion import matplotlib colors = ["#348ABD", "#7A68A6", "#A60628", "#467821", "#CF4457", "#188487", "#E24A33"] if LooseVersion(matplotlib.__version__) < LooseVersion("1.5.1"): MPL_STYLE["axes.color_cycle"] = colors else: MPL_STYLE["axes.prop_cycle"] = matplotlib.cycler("color", colors) ARGS_TO_FORWARD = ["marker", "markersize", "markevery", "linestyle", "linewidth", "drawstyle"] """kwargs that will be forwarded to matplotlib API calls """ HTML_HEIGHT = 400 """Default height for HTML based plots""" DEFAULT_SYNC_ZOOM = False """Sync Graph zoom by default in :mod:`trappy.plotter.ILinePlot` graph groups """ EVENT_PLOT_STRIDE = False """Default value for stride which enables sampled EventPlots for :mod:`trappy.plotter.EventPlot` """ PLOT_SCATTER = False
and the corresponding relaxed magnetization angles of the other islands, in order of their region numbers. """ import itertools import math import matplotlib import matplotlib.pyplot as plt import os import re import numpy as np import pandas as pd from matplotlib import cm font = {'size': 16} matplotlib.rc('font', **font) matplotlib.rcParams['axes.prop_cycle'] = matplotlib.cycler( color=["b", "y", "r", "lightgreen"]) def read_mumax3_table(filename): """Puts the mumax3 output table in a pandas dataframe""" table = pd.read_csv(filename, sep='\t') table.columns = ' '.join(table.columns).split()[1::2] return table def convert_ovf(folder): os.system('mumax3-convert -png -arrows 8 %s/*.ovf' % folder)
(1.0, 0.7, 0.0), # yellow(ish) (0.5, 0., 0.75), # magenta 'gray', (0.3, 0.7, 1.0), # light blue 'pink', (0.13671875, 0.171875, 0.0859375), # dark green (1.0, 0.4, 0.0), # orange 'saddlebrown', 'navy', ] # set mpl version dependent stuff try: from matplotlib import cycler GWPY_PLOT_PARAMS.update({ 'axes.prop_cycle': cycler('color', GWPY_COLOR_CYCLE), }) except (ImportError, KeyError): # mpl < 1.5 GWPY_PLOT_PARAMS['axes.color_cycle'] = GWPY_COLOR_CYCLE # set latex options if rcParams['text.usetex'] or USE_TEX: GWPY_PLOT_PARAMS.update({ "text.usetex": True, "font.family": "serif", "font.serif": ["Computer Modern"], "text.latex.preamble": MACROS, }) # update matplotlib rcParams with new settings rcParams.update(GWPY_PLOT_PARAMS)
def _init_mpl_rcparams(): import matplotlib as mpl from matplotlib import style #http://matplotlib.org/users/style_sheets.html nogg = ut.get_argflag('--nogg') if not nogg: style.use('ggplot') #style.use(['ggplot']) #print('style.available = %r' % (style.available,)) #style.use(['bmh']) #style.use(['classic']) #import utool #utool.embed() #style.use(['ggplot', 'dark_background']) if ut.get_argflag('--notoolbar'): toolbar = 'None' else: toolbar = 'toolbar2' mpl.rcParams['toolbar'] = toolbar #mpl.rc('text', usetex=False) if ut.get_argflag('--usetex'): #mpl.rc('text', usetex=True) mpl.rcParams['text.usetex'] = True #matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"] mpl.rcParams['text.latex.unicode'] = True mpl_keypress_shortcuts = [key for key in mpl.rcParams.keys() if key.find('keymap') == 0] for key in mpl_keypress_shortcuts: mpl.rcParams[key] = '' CUSTOM_GGPLOT = 1 if CUSTOM_GGPLOT and not nogg: ggplot_style = style.library['ggplot'] # NOQA # print('ggplot_style = %r' % (ggplot_style,)) custom_gg = { 'axes.axisbelow': True, #'axes.edgecolor': 'white', 'axes.facecolor': '#E5E5E5', 'axes.edgecolor': 'none', #'axes.facecolor': 'white', 'axes.grid': True, 'axes.labelcolor': '#555555', 'axes.labelsize': 'large', 'axes.linewidth': 1.0, 'axes.titlesize': 'x-large', 'figure.edgecolor': '0.50', 'figure.facecolor': 'white', 'font.size': 10.0, 'grid.color': 'white', 'grid.linestyle': '-', 'patch.antialiased': True, 'patch.edgecolor': '#EEEEEE', 'patch.facecolor': '#348ABD', 'patch.linewidth': 0.5, 'xtick.color': '#555555', 'xtick.direction': 'out', 'ytick.color': '#555555', 'ytick.direction': 'out', 'axes.prop_cycle': mpl.cycler('color', ['#E24A33', '#348ABD', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8']), } mpl.rcParams.update(custom_gg) NICE_DARK_BG = False if NICE_DARK_BG: dark_style = { 'axes.edgecolor': 'white', 'axes.facecolor': 'black', 'axes.labelcolor': 'white', 'figure.edgecolor': 'black', 'figure.facecolor': 'black', 'grid.color': 'white', 'lines.color': 'white', 'patch.edgecolor': 'white', 'savefig.edgecolor': 'black', 'savefig.facecolor': 'black', 'text.color': 'white', 'xtick.color': 'white', 'ytick.color': 'white' } mpl.rcParams.update(dark_style) mpl.rcParams['figure.subplot.top'] = .8
deltas, corrs, r2s = compare_ase_range( ase, best_model, ['bcdP', 'bcdP2'], small_atlas.ix[small_atlas.in_central], denom_cutoff=0, num_points=51, range_low=.05, range_high=20, ) tweaked['bcd + bcd$^2$'] = deltas, corrs, r2s corrfig = mpl.figure(figsize=(16, 6)) ax1 = mpl.subplot(1, 2, 1) ax2 = mpl.subplot(1, 2, 2) kwargs =( mplbase.cycler('linestyle', ['-', '--', '-.', ':']) *mplbase.cycler('color', ['b', 'g', 'r', 'c', 'm', 'y', 'k']) ) for (tf, (deltas, corrs, r2s)), kwarg in zip(sorted(tweaked.items()), kwargs): ax1.semilogx(deltas, corrs, basex=2, label=tf, **kwarg) ax2.semilogx(deltas, r2s.clip(-0.1, 1)*100, basex=2, label=tf, **kwarg) try: the_tf = sub('[\^\$ \+]', '', tf) best_corr = deltas[np.nanargmax(corrs)] best_r2 = deltas[np.nanargmax(r2s)] if tf == 'bcd': tfchange = {'bcdP': best_corr} elif tf == 'bcd$^2$': tfchange = {'bcdP2': best_corr}
# Meta data labels = ['20-30', '30-40', '40-50', '50-60', '60-70', '70-80'] outages = [151231, 99140, 57064, 26274, 11661, 1897] overloads = [54597, 54821, 54733, 55556, 55479, 55452] x = np.arange(len(labels)) width = 0.35 # the width of the bars print(outages) print(overloads) # Plot design metrics bmap = brewer2mpl.get_map('Set2', 'qualitative', 7) colors = bmap.mpl_colors params = { 'axes.prop_cycle': mpl.cycler(color=colors), 'axes.labelsize': 8, 'text.usetex': False, 'font.size': 8, 'font.family': 'serif', 'legend.fontsize': 8, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'figure.figsize': [3.5, 2.5] } mpl.rcParams.update(params) # Plot fig = plt.figure() ax = fig.add_subplot(111) # Data
def banskt_presentation(black = '#333333', linewidth = 2, ticksize = 8, fontsize = 28, padding = 10, fontfamily = 'latex', colors = 'banskt'): if colors == 'banskt': mcolors = banskt_colors() elif colors == 'kelly': mcolors = kelly_colors() if fontfamily == 'latex': matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage[sfdefault,scaled=.85, lining]{FiraSans}', r'\usepackage[cmintegrals]{newtxsf}', r'\usepackage{microtype}', ] matplotlib.rcParams['text.usetex'] = True elif fontfamily == 'latex-clearsans': matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage[scaled=.86]{ClearSans}', r'\usepackage[libertine]{newtxmath}', r'\usepackage{microtype}', ] elif fontfamily == 'system': matplotlib.rcParams['font.family'] = 'sans-serif' matplotlib.rcParams['font.sans-serif'] = 'DejaVu Sans' matplotlib.rcParams['mathtext.fontset'] = 'stixsans' # Size matplotlib.rcParams['figure.figsize'] = 8, 8 # Fonts matplotlib.rcParams['font.size'] = fontsize matplotlib.rcParams['text.color'] = black matplotlib.rcParams['axes.titlesize'] = fontsize * 1.2 matplotlib.rcParams['axes.labelsize'] = fontsize matplotlib.rcParams['axes.labelweight'] = 'normal' matplotlib.rcParams['axes.labelcolor'] = black matplotlib.rcParams['xtick.labelsize'] = fontsize matplotlib.rcParams['ytick.labelsize'] = fontsize matplotlib.rcParams['legend.fontsize'] = fontsize # Axes matplotlib.rcParams['axes.titlepad'] = 50 matplotlib.rcParams['axes.edgecolor'] = black matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['axes.labelpad'] = 20 matplotlib.rcParams['axes.linewidth'] = linewidth # Legend matplotlib.rcParams['legend.facecolor'] = 'inherit' matplotlib.rcParams['legend.edgecolor'] = black matplotlib.rcParams['legend.frameon'] = False matplotlib.rcParams['legend.numpoints'] = 1 matplotlib.rcParams['legend.scatterpoints'] = 1 matplotlib.rcParams['legend.markerscale'] = 1.0 # Dimensions as fraction of fontsize matplotlib.rcParams['legend.borderpad'] = 0 matplotlib.rcParams['legend.labelspacing'] = 0.3 matplotlib.rcParams['legend.handlelength'] = 0.5 matplotlib.rcParams['legend.handleheight'] = 0.9 matplotlib.rcParams['legend.handletextpad'] = 0.5 # Ticks matplotlib.rcParams['xtick.major.top'] = False matplotlib.rcParams['xtick.major.bottom'] = True matplotlib.rcParams['xtick.minor.top'] = False matplotlib.rcParams['xtick.minor.bottom'] = False matplotlib.rcParams['ytick.major.left'] = True matplotlib.rcParams['ytick.major.right'] = False matplotlib.rcParams['ytick.minor.left'] = False matplotlib.rcParams['ytick.minor.right'] = False matplotlib.rcParams['xtick.major.size'] = ticksize matplotlib.rcParams['xtick.minor.size'] = 2 * ticksize / 3.0 matplotlib.rcParams['ytick.major.size'] = ticksize matplotlib.rcParams['ytick.minor.size'] = 2 * ticksize / 3.0 matplotlib.rcParams['xtick.major.pad'] = padding matplotlib.rcParams['xtick.minor.pad'] = padding matplotlib.rcParams['ytick.major.pad'] = padding matplotlib.rcParams['ytick.minor.pad'] = padding matplotlib.rcParams['xtick.major.width'] = linewidth matplotlib.rcParams['xtick.minor.width'] = linewidth matplotlib.rcParams['ytick.major.width'] = linewidth matplotlib.rcParams['ytick.minor.width'] = linewidth matplotlib.rcParams['xtick.color'] = black matplotlib.rcParams['ytick.color'] = black # Color cycle matplotlib.rcParams['axes.prop_cycle'] = cycler('color', mcolors) # Histogram matplotlib.rcParams['hist.bins'] = 20 # Patches # matplotlib.rcParams['patch.facecolor'] = mcolors[0] # doesn't have any effect, comes from prop_cycle matplotlib.rcParams['patch.edgecolor'] = black matplotlib.rcParams['patch.linewidth'] = linewidth / 2 matplotlib.rcParams['patch.force_edgecolor'] = True # For scatter plot, show only left and bottom axes #matplotlib.rcParams['axes.spines.left'] = True #matplotlib.rcParams['axes.spines.bottom'] = True #matplotlib.rcParams['axes.spines.top'] = False #matplotlib.rcParams['axes.spines.right'] = False return
def __init__(self, N_0, S_0, I_0, A_0, R_0, lambd, mu, mu_star, gamma, gamma_star, beta_1, beta_2, beta_3, beta_4): assert (N_0 == S_0 + I_0 + A_0 + R_0) linspace = range(61) y_0 = (N_0, S_0, I_0, A_0, R_0) sol = odeint(self.f, y_0, linspace, args=(lambd, mu, mu_star, gamma, gamma_star, beta_1, beta_2, beta_3, beta_4)) N, S, I, A, R = np.split(sol, range(1, 5), axis=1) N = N[:, 0] S = S[:, 0] I = I[:, 0] A = A[:, 0] R = R[:, 0] plt.figure(1) plt.title('Predicciones evolución epidemia') plt.subplot(2, 2, 1, title='Totales') plt.plot(linspace, sol[:, 0], color='k') ax = plt.gca() ax.ticklabel_format(useOffset=False) plt.subplot(2, 2, 2, title='Susceptibles') plt.plot(linspace, sol[:, 0], color='b') ax = plt.gca() ax.ticklabel_format(useOffset=False) mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=['r', 'y']) plt.subplot(2, 2, 3, title='Infectados y asintomáticos') plt.plot(linspace, sol[:, 2:4]) plt.legend(['Infectados', 'Asintomáticos'], loc='upper right') plt.subplot(2, 2, 4, title='Recuperados') plt.plot(linspace, sol[:, 4], color='g') fallecidos = mu_star * I contagiados_por_infectado = beta_1 * np.multiply(S, I) contagiados_por_asintomatico = beta_3 * np.multiply(S, A) plt.figure(2) plt.title('Curvas diarias') plt.subplot(1, 2, 1, title='Fallecimientos diarios') plt.plot(fallecidos, color='k') plt.subplot(1, 2, 2, title='Contagios diarios') plt.plot(contagiados_por_infectado, color='r') plt.plot(contagiados_por_asintomatico, color='y') plt.plot(contagiados_por_infectado + contagiados_por_asintomatico, color='b') plt.legend([ 'Contagios por infectado', 'Contagios por asintomático', 'Contagios totales' ]) fallecidos_totales = np.sum(fallecidos) contagios_totales = np.sum(contagiados_por_infectado + contagiados_por_asintomatico) ratio_contagios_asintomaticos = np.sum( contagiados_por_asintomatico) / contagios_totales print('Fallecidos en los siguiente 60 días:', fallecidos_totales) print('Contagios en los siguiente 60 días:', contagios_totales) print('Porcentaje de contagios por asintomático:', ratio_contagios_asintomaticos * 100) print('Fallecidos por asintomático:', ratio_contagios_asintomaticos * fallecidos_totales)
import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib import collections as mc from matplotlib.legend_handler import HandlerTuple import itertools as itr import math import colorcet as cc adc_min = -5 adc_max = 20 cmap_ed = cc.cm.kbc_r marker_size = 5 """define default color cycle from colorcet""" mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=cc.glasbey_warm) color_noise = "#c7c7c7" color_clustered = "#ffb77d" color_matched1 = "#28568f" color_matched2 = "#abdf7f" color_track2d = "#de425b" color_track3d = "#00a9b2" def draw_hits(pos, time, z=[], ax=None, **kwargs): ax = plt.gca() if ax is None else ax if(len(pos) == 0): return ax
'axes.titlesize': 24, 'xtick.labelsize': 16, 'ytick.labelsize': 16, }) if mpl_version < '2.0': DEFAULT_PARAMS['font.serif'] = ['Computer Modern'] # build better default colour cycle for matplotlib < 2 if mpl_version < '2.0': try: from matplotlib import cycler except (ImportError, KeyError): # mpl < 1.5 DEFAULT_PARAMS['axes.color_cycle'] = DEFAULT_COLORS else: # mpl >= 1.5 DEFAULT_PARAMS.update({ 'axes.prop_cycle': cycler('color', DEFAULT_COLORS), }) # remove rcParams for old matplotlib # https://matplotlib.org/1.5.1/users/whats_new.html#configuration-rcparams if mpl_version < '1.5': for key in ( 'axes.labelpad', 'legend.edgecolor', ): DEFAULT_PARAMS.pop(key, None) # update matplotlib rcParams with new settings rcParams.update(DEFAULT_PARAMS) # -- dynamic subplot positioning ----------------------------------------------