def pic_switch(event): bounds = roi1.export() if zoom.value_selected == 'Zoom': axpic.cla() axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected) axpic.set_title(start.file_list[int(pic_swap.val)]) axpic.set_xlim(bounds[2], bounds[3]) axpic.set_ylim(bounds[1], bounds[0]) axpic.axvline(x=bounds[2]) axpic.axvline(x=bounds[3]) axpic.axhline(y=bounds[0]) axpic.axhline(y=bounds[1]) axbar.cla() norm = Normalize(vmin=vmin.val, vmax=vmax.val) col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal') col.set_ticks([vmin.val, vmax.val], update_ticks=True) else: axpic.cla() axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected) axpic.set_title(start.file_list[int(pic_swap.val)]) axpic.axvline(x=bounds[2]) axpic.axvline(x=bounds[3]) axpic.axhline(y=bounds[0]) axpic.axhline(y=bounds[1]) axbar.cla() norm = Normalize(vmin=vmin.val, vmax=vmax.val) col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal') col.set_ticks([vmin.val, vmax.val], update_ticks=True)
def axplot_bmus(ax, bmus, num_clusters, lab): 'axes plot bmus series using colors' # colors wt_colors = GetClusterColors(num_clusters) # prepare nans as white bmus = bmus.fillna(num_clusters + 1) wt_colors = np.vstack([wt_colors, [0, 0, 0]]) # bmus colors vp = wt_colors[bmus.astype(int) - 1] # listed colormap ccmap = mcolors.ListedColormap(vp) # color series cbar_x = ColorbarBase( ax, cmap=ccmap, orientation='horizontal', norm=mcolors.Normalize(vmin=0, vmax=num_clusters), ) cbar_x.set_ticks([]) # customize axes ax.set_xticks([]) ax.set_yticks([]) ax.set_ylabel(lab, rotation=0, fontweight='bold', labelpad=35)
def scale(args): """ Draws the variable scale that is placed over the map. Returns a BytesIO object. """ dataset_name = args.get("dataset") config = DatasetConfig(dataset_name) scale = args.get("scale") scale = [float(component) for component in scale.split(",")] variable = args.get("variable") variable = variable.split(",") if len(variable) > 1: variable_unit = config.variable[",".join(variable)].unit variable_name = config.variable[",".join(variable)].name else: variable_unit = config.variable[variable[0]].unit variable_name = config.variable[variable[0]].name cmap = colormap.find_colormap(variable_name) if len(variable) == 2: cmap = colormap.colormaps.get("speed") fig = plt.figure(figsize=(2, 5), dpi=75) ax = fig.add_axes([0.05, 0.05, 0.25, 0.9]) norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1]) formatter = ScalarFormatter() formatter.set_powerlimits((-3, 4)) bar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation="vertical", format=formatter) if variable_name == "Potential Sub Surface Channel": bar.set_ticks([0, 1], True) bar.set_label("%s (%s)" % (variable_name.title(), utils.mathtext(variable_unit)), fontsize=12) # Increase tick font size bar.ax.tick_params(labelsize=12) buf = BytesIO() plt.savefig( buf, format="png", dpi="figure", transparent=False, bbox_inches="tight", pad_inches=0.05, ) plt.close(fig) buf.seek(0) # Move buffer back to beginning return buf
def plot_colors(c, figsize=(10, 1), ticks=False, **kwargs): """ Plot a horizontal colorbar to inspect colors Parameters ---------- c : array-like or Colormap instance Iterable containing colors. A :obj:`~numpy.ndarray` with 3 dimensions will be interpreted as RBA(A). figsize : tuple, optional Matplotlib figsize parameter ticks : bool, optional Add ticks to the figure **kwargs Parameters for `plt.ColorBase` """ plt.rcParams['savefig.pad_inches'] = 0 if isinstance(c, (list, tuple, np.ndarray)): c = np.array(c) N = c.shape[0] cmap = LinearSegmentedColormap.from_list('plot', c, N=N) elif isinstance(c, colors.Colormap): N = c.N cmap = c fig, ax = plt.subplots(figsize=figsize) bounds = np.linspace(0, 1, N + 1) if N < 256: norm = colors.BoundaryNorm(bounds, N) cb = ColorbarBase(ax, cmap=cmap, norm=norm, spacing='proportional', ticks=None, boundaries=bounds, format='%1i', orientation=u'horizontal', **kwargs) ax.patch.set_edgecolor('black') if not ticks: plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False) # labels along the bottom edge are off else: cb.set_ticks(np.linspace(1 / (2 * N), 1 - 1 / (2 * N), N)) cb.set_ticklabels(np.arange(N))
def spikesplot_cb(position, cmap='viridis', fig=None): # Add colorbar if fig is None: fig = plt.gcf() cax = fig.add_axes(position) cb = ColorbarBase(cax, cmap=get_cmap(cmap), spacing='proportional', orientation='horizontal', drawedges=False) cb.set_ticks([0, 0.5, 1.0]) cb.set_ticklabels(['Inferior', '(axial slice)', 'Superior']) cb.outline.set_linewidth(0) cb.ax.xaxis.set_tick_params(width=0) return cax
def spikesplot_cb(position, cmap='viridis', fig=None): # Add colorbar if fig is None: fig = plt.gcf() cax = fig.add_axes(position) cb = ColorbarBase(cax, cmap=cm.get_cmap(cmap), spacing='proportional', orientation='horizontal', drawedges=False) cb.set_ticks([0, 0.5, 1.0]) cb.set_ticklabels(['Inferior', '(axial slice)', 'Superior']) cb.outline.set_linewidth(0) cb.ax.xaxis.set_tick_params(width=0) return cax
def plot_colorbar(cax, cmap, cnorm, hue_norm, linewidth=0.5): if isinstance(cmap, str): cmap = get_cmap(cmap) colorbar = ColorbarBase(cax, cmap=cmap, norm=cnorm, orientation='vertical', extend='both') colorbar_ticks = [hue_norm[0], sum(hue_norm) / 2, hue_norm[1]] # TODO automatic ticklabel format, auto sci-format, float trim etc colorbar_ticklabels = list(map(lambda i: f'{i:.1f}', colorbar_ticks)) colorbar.set_ticks(colorbar_ticks) colorbar.set_ticklabels(colorbar_ticklabels) colorbar.outline.set_linewidth(linewidth) colorbar.ax.tick_params(size=1, pad=1, width=linewidth, length=0.3) return cax
def pick_colors(ax, df, attr, cmap): from matplotlib.colorbar import ColorbarBase colors = Colors(cmap, df[attr]) bar = ColorbarBase( ax, norm=colors.norm, cmap=colors.cmap, boundaries=colors.boundaries, ) bar.set_ticks(colors.ticks) bar.set_ticklabels(colors.ticklabels) ax.invert_yaxis() return colors
def display_median_price_animation(self): """Kicks off the animation of median price information.""" fig = plotter.figure(num = 1, figsize = (10, 12), tight_layout = True) fig.canvas.set_window_title('Percent increase in median house ' + \ 'price since 1996') axis = fig.add_axes([0.85, 0.04, 0.03, 0.92]) colorbar_ticks = [0, .2, .4, .6, .8, 1.0] colorbar_labels = ['-100%', '0%', '250%', '500%', '750%', '>1000%'] colorbar = ColorbarBase(axis, self._colormap, orientation='vertical') colorbar.set_ticks(colorbar_ticks) colorbar.set_ticklabels(colorbar_labels) fig.add_axes([0.0, 0.0, 0.82, 1.0]) anim = FuncAnimation(fig, self._animate, frames = self.endyear + 1 - self.startyear, interval = 1000, blit = True, init_func = self._init_animate, repeat_delay = 3000) plotter.show()
def display_median_price_animation(self): """Kicks off the animation of median price information.""" fig = plotter.figure(num=1, figsize=(10, 12), tight_layout=True) fig.canvas.set_window_title('Percent increase in median house ' + \ 'price since 1996') axis = fig.add_axes([0.85, 0.04, 0.03, 0.92]) colorbar_ticks = [0, .2, .4, .6, .8, 1.0] colorbar_labels = ['-100%', '0%', '250%', '500%', '750%', '>1000%'] colorbar = ColorbarBase(axis, self._colormap, orientation='vertical') colorbar.set_ticks(colorbar_ticks) colorbar.set_ticklabels(colorbar_labels) fig.add_axes([0.0, 0.0, 0.82, 1.0]) anim = FuncAnimation(fig, self._animate, frames=self.endyear + 1 - self.startyear, interval=1000, blit=True, init_func=self._init_animate, repeat_delay=3000) plotter.show()
def plot(): global DATA, store c = Config(args.config) conf = PlotConf() conf = conf.new_child(c['scatterplot'].get('conf', {})) attrs = store.get_storer(path).attrs if hasattr(attrs, 'config') and conf.get('conf_overwrite', False): attrs.config['scatterplot'] = {} c.append(attrs.config) if not DATA.empty and 'newfields' in conf: for field, expr in conf['newfields'].items(): logging.debug("executing DATA[{}] = {}]".format(field, expr)) DATA[field] = eval(expr) logging.debug("done.") pcount = 0 for p in c['scatterplot']['plots']: lcount = 0 pconf = conf.new_child(p) plt.cla() plt.clf() plt.rcParams.update(pconf['rcParams']) if pconf['figsize']: plt.figure(figsize=pconf['figsize']) else: plt.figure() if pconf['fontsize'] != conf['fontsize']: plt.rcParams.update({'font.size': pconf['fontsize']}) if pconf['colorbar_only']: plt.figure(figsize=(8, 0.25)) ax = plt.gca() norm = Normalize(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) if pconf['z-axis']['lognorm']: norm = LogNorm(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) cbar = ColorbarBase( ax, norm=norm, cmap=pconf['cmap'], orientation=pconf['z-axis']['colorbar_orientation']) if pconf['z-axis']['colorbar_orientation'] == 'horizontal': ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') if pconf['z-axis']['label']: cbar.set_label(pconf['z-axis']['label']) if pconf['z-axis']['ticks']: cbar.set_ticks(pconf['z-axis']['ticks']) plt.savefig(pconf['filename'], bbox_inches='tight') plt.figure() continue if pconf['title']: plt.title(conf['title']) if 'plots' not in p: p['plots'] = [p] for l in p['plots']: # noqa: E741 lconf = pconf.new_child(l) label = lconf['label'] label = label if label else None cmap = lconf['cmap'] zorder = lconf.get('zorder', lcount) color = lconf.get('color', "C{}".format(lcount)) x = lconf.get('x-field', lconf['x-axis'].get('field', None)) y = lconf.get('y-field', lconf['y-axis'].get('field', None)) z = lconf.get('z-field', lconf['z-axis'].get('field', None)) xlabel = lconf['x-axis']['label'] ylabel = lconf['y-axis']['label'] zlabel = lconf['z-axis']['label'] if hasattr(c, 'parameters'): xlabel = c.parameters.get( x, {'latex': xlabel})['latex'] if not xlabel else xlabel ylabel = c.parameters.get( y, {'latex': ylabel})['latex'] if not ylabel else ylabel zlabel = c.parameters.get( z, {'latex': zlabel})['latex'] if not zlabel else zlabel if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) if lconf['hline']: plt.axhline(y=y, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if lconf['vline']: plt.axvline(x=x, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if hasattr(c, 'parameters'): x = c.parameters.get(x, {'lha': x})['lha'] y = c.parameters.get(y, {'lha': y})['lha'] z = c.parameters.get(z, {'lha': z})['lha'] PDATA = DATA for constr in lconf['constraints']: PDATA = PDATA[eval(constr)] if (lconf['datafile'] and lconf['datafile'] != conf['datafile']): conf['datafile'] = lconf['datafile'] # TODO store.close() del DATA, PDATA, store store = HDFStore(lconf['datafile']) # TODO DATA = store['results'] # TODO PDATA = DATA if not PDATA.empty and 'newfields' in conf: for field, expr in conf['newfields'].items(): logging.debug("executing PATA[{}] = {}]".format( field, expr)) PDATA[field] = eval(expr) logging.debug("done.") for ax, field in {'x-axis': x, 'y-axis': y, 'z-axis': z}.items(): bounds = lconf[ax]['boundaries'] if len(bounds) == 2: logging.debug( "applying boundaries [{},{}] on axis {}, field {}". format(bounds[0], bounds[1], ax, field)) PDATA = PDATA[(PDATA[field] >= bounds[0]) & (PDATA[field] <= bounds[1])] if lconf['x-axis']['lognorm']: if type(lconf['x-axis']['lognorm']) == str: plt.xscale(lconf['x-axis']['lognorm']) else: plt.xscale('log') if lconf['y-axis']['lognorm']: if type(lconf['y-axis']['lognorm']) == str: plt.yscale(lconf['y-axis']['lognorm']) else: plt.yscale('log') if z: PDATA = PDATA.sort_values(by=z) color = PDATA[z] vmin = PDATA[z].min( ) if not lconf['z-axis']['vmin'] else lconf['z-axis']['vmin'] vmax = PDATA[z].max( ) if not lconf['z-axis']['vmax'] else lconf['z-axis']['vmax'] else: vmin = None vmax = None znorm = LogNorm(vmin=vmin, vmax=vmax) if lconf['z-axis']['lognorm'] else None if lconf['exec']: exec(lconf['exec']) if len(PDATA) == 0: logging.error( 'In plot {}, x:{} , y:{}; no data to plot! (wrong boundaries or constraints?)' .format(p['filename'], x, y)) continue if pconf.get('type', 'scatter') == 'scatter': cs = plt.scatter(PDATA[x], PDATA[y], zorder=zorder, label=label, cmap=cmap, c=color, vmin=vmin, vmax=vmax, norm=znorm, s=lconf['s'], alpha=lconf['alpha'], marker=lconf.get('marker', None)) else: PDATA = PDATA[[x, y]].dropna().sort_values(by=x) cs = plt.plot(PDATA[x], PDATA[y], lconf.get('fmt', '.'), zorder=zorder, c=color, alpha=lconf['alpha'], label=label, **lconf.get('kwargs', {})) plt.grid(b=True, which='major', color='#777777', linestyle='-', alpha=0.3, zorder=0) plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.1, zorder=0) plt.margins(x=0.01, y=0.01) # TODO if lconf['x-axis']['ticks']: if type(lconf['x-axis']['ticks'][0]) is not list: lconf['x-axis']['ticks'] = [ lconf['x-axis']['ticks'], ['${}$'.format(xt) for xt in lconf['x-axis']['ticks']] ] plt.xticks(lconf['x-axis']['ticks'][0], lconf['x-axis']['ticks'][1]) if lconf['y-axis']['ticks']: if type(lconf['y-axis']['ticks'][0]) is not list: lconf['y-axis']['ticks'] = [ lconf['y-axis']['ticks'], ['${}$'.format(yt) for yt in lconf['y-axis']['ticks']] ] plt.yticks(lconf['y-axis']['ticks'][0], lconf['y-axis']['ticks'][1]) if lconf['z-axis']['colorbar']: cbar = plt.colorbar( cs, orientation=lconf['z-axis']['colorbar_orientation'], **lconf['z-axis'].get('kwargs', {})) if zlabel: cbar.set_label(zlabel) if lconf['z-axis']['ticks']: if type(lconf['z-axis']['ticks'][0]) is not list: lconf['z-axis']['ticks'] = [ lconf['z-axis']['ticks'], [ '${}$'.format(zt) for zt in lconf['z-axis']['ticks'] ] ] cbar.set_ticks(lconf['z-axis']['ticks']) for label in cbar.ax.yaxis.get_ticklabels(): if lconf['z-axis']['colorbar_orientation'] == 'horizontal': label.set_ha('center') else: label.set_va('center') lcount += 1 if pconf['textbox'] and 'text' in pconf['textbox']: bbox = pconf['textbox'].get( 'bbox', dict(boxstyle='round', facecolor='white', alpha=0.2)) va = pconf['textbox'].get('va', 'top') ha = pconf['textbox'].get('ha', 'left') textsize = pconf['textbox'].get( 'fontsize', pconf['rcParams'].get('font.size', 15)) xtext = pconf['textbox'].get('x', 0.95) ytext = pconf['textbox'].get('y', 0.85) plt.gcf().text(xtext, ytext, pconf['textbox']['text'], fontsize=textsize, va=va, ha=ha, bbox=bbox) if pconf['tick_params']: plt.tick_params(**pconf['tick_params']) ax = plt.gca() for label in ax.yaxis.get_ticklabels(): label.set_verticalalignment('center') for label in ax.xaxis.get_ticklabels(): label.set_horizontalalignment('center') for ann in p.get('annotiations', []): plt.annotate(ann['label'], ann['pos'], **ann.get('kwargs', {})) if any([lbl.get('label', False) for lbl in p['plots']]): plt.legend(**pconf['legend']) plotfile = DIR + p.get('filename', 'plot{}.png'.format(pcount)) logging.info("Saving {}.".format(plotfile)) plt.savefig(plotfile, bbox_inches="tight", dpi=pconf['dpi']) pcount += 1
def plotter(fdict): """ Go """ pgconn = get_dbconn("asos") ctx = get_autoplot_context(fdict, get_description()) station = ctx["zstation"] date = ctx["date"] opt = ctx["opt"] varname = ctx["v"] tzname = ctx["_nt"].sts[station]["tzname"] # Resolve how to limit the query data limiter = "" if opt == "day": limiter = (f" and to_char(valid at time zone '{tzname}', 'mmdd') = " f"'{date.strftime('%m%d')}' ") subtitle = (f"For Date of {date.strftime('%-d %b')}, " f"{date.strftime('%-d %b %Y')} plotted in bottom panel") datefmt = "%I %p" elif opt == "week": limiter = f" and extract(week from valid) = {date.strftime('%V')} " subtitle = ( f"For ISO Week of {date.strftime('%V')}, " f"week of {date.strftime('%-d %b %Y')} plotted in bottom panel") datefmt = "%-d %b" elif opt == "month": limiter = f" and extract(month from valid) = {date.strftime('%m')} " subtitle = (f"For Month of {date.strftime('%B')}, " f"{date.strftime('%b %Y')} plotted in bottom panel") datefmt = "%-d" else: subtitle = f"All Year, {date.year} plotted in bottom panel" datefmt = "%-d %b" # Load up all the values, since we need pandas to do some heavy lifting obsdf = read_sql( f""" select valid at time zone 'UTC' as utc_valid, extract(year from valid at time zone %s) as year, extract(hour from valid at time zone %s + '10 minutes'::interval)::int as hr, {varname} from alldata WHERE station = %s and {varname} is not null {limiter} and report_type = 2 ORDER by valid ASC """, pgconn, params=(tzname, tzname, station), index_col=None, ) if obsdf.empty: raise NoDataFound("No data was found.") # Assign percentiles obsdf["quantile"] = obsdf[["hr", varname]].groupby("hr").rank(pct=True) # Compute actual percentiles qtile = (obsdf[["hr", varname ]].groupby("hr").quantile(np.arange(0, 1.01, 0.05)).reset_index()) qtile = qtile.rename(columns={"level_1": "quantile"}) (fig, ax) = plt.subplots(2, 1) cmap = get_cmap(ctx["cmap"]) for hr, gdf in qtile.groupby("hr"): ax[0].plot( gdf["quantile"].values * 100.0, gdf[varname].values, color=cmap(hr / 23.0), label=str(hr), ) ax[0].set_xlim(0, 100) ax[0].grid(True) ax[0].set_ylabel(PDICT[varname]) ax[0].set_xlabel("Percentile") ax[0].set_position([0.13, 0.55, 0.71, 0.34]) cax = plt.axes([0.86, 0.55, 0.03, 0.33], frameon=False, yticks=[], xticks=[]) cb = ColorbarBase(cax, cmap=cmap) cb.set_ticks(np.arange(0, 1, 4.0 / 24.0)) cb.set_ticklabels(["Mid", "4 AM", "8 AM", "Noon", "4 PM", "8 PM"]) cb.set_label("Local Hour") thisyear = obsdf[obsdf["year"] == date.year] if not thisyear.empty: ax[1].plot(thisyear["utc_valid"].values, thisyear["quantile"].values * 100.0) ax[1].grid(True) ax[1].set_ylabel("Percentile") ax[1].set_ylim(-1, 101) ax[1].xaxis.set_major_formatter( mdates.DateFormatter(datefmt, tz=pytz.timezone(tzname))) if opt == "day": ax[1].set_xlabel(f"Timezone: {tzname}") title = ("%s %s %s Percentiles\n%s") % ( station, ctx["_nt"].sts[station]["name"], PDICT[varname], subtitle, ) fitbox(fig, title, 0.01, 0.99, 0.91, 0.99, ha="center", va="center") return fig, qtile
def PlotExpansionOnApproach(zs=numpy.linspace(.1,300,100),a=30,beta=1,Nterms=5,\ *args,**kwargs): approach=GetExpansionApproachCurve(zs=zs,a=a,beta=1,Nterms=Nterms,*args,**kwargs) from matplotlib.collections import LineCollection from common import plotting #just for the BWR colormap figure() subplot(121) for i in range(Nterms): pole=approach['Ps'][:,i] x,y=pole.real,-pole.imag points = numpy.array([x, y]).T.reshape(-1, 1, 2) segments = numpy.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=get_cmap('jet_r'), norm=Normalize(zs.min(),zs.max())) #use reversed colormap - lower values of freq are red lc.set_array(zs) lc.set_linewidth(2) gca().add_collection(lc) gca().set_xscale('log') gca().set_yscale('log') gca().set_aspect('equal') xlim(1e-1,1e4) xlabel(r'$\mathrm{Re}(\mathcal{P}_j)$') ylabel(r'$-\mathrm{Im}(\mathcal{P}_j)$') grid() subplot(122) for i in range(Nterms): pole=approach['Ps'][:,i] coeff=1j*approach['Rs'][:,i] #-1 is to put on same footing as dipole radiation, 1j was missing as prefactor to green's function #if i==0: p=numpy.angle(coeff[0]) #coeff*=numpy.exp(-1j*p) #numpy.abs(coeff).plot(plotter=semilogx) #plot(coeff.real,coeff.imag,ls='',marker='') x,y=coeff.real,coeff.imag points = numpy.array([x, y]).T.reshape(-1, 1, 2) segments = numpy.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=get_cmap('jet_r'), norm=Normalize(zs.min(),zs.max())) #use reversed colormap - lower values of freq are red lc.set_array(zs) lc.set_linewidth(2) gca().add_collection(lc) gca().set_aspect('equal') xlim(-.15e8,1.35e8) ylim(-.1e8,1.1e8) xticks(numpy.array([0,2.5,5,7.5,10,12.5])*1e7,\ ['0','2.5','5','7.5','10','12.5']) yticks(numpy.array([0,2.5,5,7.5,10])*1e7,\ ['0','2.5','5','7.5','10']) xlabel(r'$\mathrm{Re}(\mathcal{R}_j)\,[a.u.]$') ylabel(r'$\mathrm{Im}(\mathcal{R}_j)\,[a.u.]$') grid() gcf().set_size_inches([12.5,6],forward=True) subplots_adjust(wspace=.35) #Put colorbar for z-height colors# from matplotlib.colorbar import ColorbarBase cax=gcf().add_axes([.275,.265,.16,.25/7.]) norm=Normalize(vmin=0,vmax=zs.max()/numpy.float(a)) cbar=ColorbarBase(cax,cmap=cm.get_cmap('jet_r'),norm=norm,orientation='horizontal') gca().xaxis.set_label_position('top') gca().xaxis.set_ticks_position('top') cbar.set_ticks((0,2.5,5,7.5,10)) xlabel('$d/a$',va='bottom',fontsize=18,labelpad=7) #labelpad to raise it a little, otherwise bbox patch will overlap xticks props=dict(boxstyle='round', facecolor='white', linewidth=0 , alpha=0.8) gca().xaxis.get_label().set_bbox(props) xticks(fontsize=13) for t in xticks()[1]: t.set_bbox(props) return approach
def axplot_ChangeProbs(ax, change_probs, wt_colors, ttl='', vmin=0, vmax=1, cmap='Blues', cbar_ttl=''): 'axes plot cluster change probabilities' num_clusters = change_probs.shape[0] # clsuter transition plot pc = ax.pcolor( change_probs, cmap=cmap, vmin=vmin, vmax=vmax, ) # add colorbar cbar = plt.colorbar(pc, ax=ax) cbar.ax.tick_params(labelsize=8) if vmin != 0 or vmax != 1: cbar.set_ticks(np.linspace(vmin, vmax, 6)) cbar.ax.set_ylabel(cbar_ttl, rotation=270, labelpad=20) # customize axes ax.set_xticks(np.arange(num_clusters) + 0.5) ax.set_yticks(np.arange(num_clusters) + 0.5) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_title(ttl, {'fontsize': 10, 'fontweight': 'bold'}) # add custom color axis ccmap = mcolors.ListedColormap([tuple(r) for r in wt_colors]) # custom color axis positions ax_pos = ax.get_position() cax_x_pos = [ax_pos.x0, ax_pos.y0 - 0.03, ax_pos.width, 0.02] cax_y_pos = [ ax_pos.x0 - 0.03 / _faspect, ax_pos.y0, 0.02 / _faspect, ax_pos.height ] # custom color axis X cax_x = ax.figure.add_axes(cax_x_pos) cbar_x = ColorbarBase( cax_x, cmap=ccmap, orientation='horizontal', norm=mcolors.Normalize(vmin=0, vmax=num_clusters), ) cbar_x.set_ticks([]) # custom color axis Y cax_y = ax.figure.add_axes(cax_y_pos) cbar_y = ColorbarBase( cax_y, cmap=ccmap, orientation='vertical', norm=mcolors.Normalize(vmin=0, vmax=num_clusters), ) cbar_y.set_ticks([])
def change_cbar_text(cbar: ColorbarBase, tick: List[Number_T], text: List[str]): cbar.set_ticks(tick) cbar.set_ticklabels(text)
def plot_slice(vstruct, scentre, snormal, cell_size=None, contourf=True, cmap='viridis', cmap_range=(None, None), bval=np.nan, cbar_tick_rot=0, show_corners=True, orientation=None, alter_bbox=(0., 0., 0., 0.), angle_step=1., dist_tol=1e-5, min_voxels=None, max_voxels=None): """ Parameters ---------- vstruct: dict scentre: Tuple point on slice plane (x, y, z) snormal: Tuple norma of slice plane (x, y, z) cell_size: float length of discretised cells. If None, cell_size = <minimum cube length> * 0.01 contourf: bool or list of bools use filled contour, else lines. If list, set independantly for each element cmap: str or list of str cmap type. If list, set independantly for each element cmap_range: tuple or list of tuples range for colors. If list, set independantly for each element bval: float or list of floats value to set as background for contour plots. If list, set independantly for each element cbar_tick_rot: float rotation of colorbar axis tick labels show_corners: bool of list of bool whether to show real space (x,y,z) plot corner positions. If list, set independantly for each element orientation: int or None between 0 and 3, select a specific bbox orientation (rotated by orientation * 90 degrees) if None, the orientation is selected such that corner min(x',y') -> min(x,y,z) alter_bbox: tuple of floats move edges of computed bbox (bottom, top, left, right) angle_step: float angular step (degrees) for mapping plane intersection with bounding box dist_tol: float distance tolerance for finding edge of bounding box min_voxels : int minimum number of voxels in cartesian density cube max_voxels : int maximum number of voxels in cartesian density cube Returns ------- fig: matplotlib.figure.Figure final_axes: list [(ax, cbar_ax), ...] for each element """ # cbar_fmt: matplotlib.ticker.Formatter # formatter for converting colorbar tick labels to str, if None use scientific notation new_struct = apply_transforms(vstruct) acceptable_elements = [ e for e in new_struct["elements"] if e["type"] in ["repeat_cell", "repeat_density"] ] num_elements = len(acceptable_elements) if num_elements == 0: raise ValueError( "no 'repeat_cell' or 'repeat_density' elements present in vstruct") if isinstance(contourf, bool): contourf = [contourf for _ in range(num_elements)] if not (isinstance(cmap, list) or isinstance(cmap, tuple)): cmap = [cmap for _ in range(num_elements)] if not (isinstance(bval, list) or isinstance(bval, tuple)): bval = [bval for _ in range(num_elements)] if not (isinstance(cmap_range, list)): cmap_range = [cmap_range for _ in range(num_elements)] if isinstance(show_corners, bool): show_corners = [show_corners for _ in range(num_elements)] # fig = plt.figure() # ax = fig.add_subplot(111, aspect='equal') # type: Axes fig, axes = plt.subplots(1, num_elements, subplot_kw={"aspect": "equal"}, sharex='all', sharey='all', squeeze=True) fig = fig # type: Figure if num_elements == 1: axes = [axes] final_axes = [] for element, ax, el_contourf, el_cmap, el_bval, ( el_vmin, el_vmax), el_corners in zip(new_struct["elements"], axes, contourf, cmap, bval, cmap_range, show_corners): ax = ax # type: Axes if element["type"] == "repeat_density": cbar_title = "{0} ({1})".format(element["name"], element["dtype"]) print("running cube_frac2cart") out = cube_frac2cart(element['dcube'], element['cell_vectors']['a'], element['cell_vectors']['b'], element['cell_vectors']['c'], element['centre'], max_voxels=max_voxels, min_voxels=min_voxels, make_cubic=False) ccube, (xmin, ymin, zmin), (xmax, ymax, zmax) = out print("running cubesliceplane") corners, corners_xy, gvalues_xy = cubesliceplane( ccube, (xmin, xmax, ymin, ymax, zmin, zmax), scentre, snormal, cell_size=cell_size, bval=el_bval, orientation=orientation, alter_bbox=alter_bbox, angle_step=angle_step, dist_tol=dist_tol) x, y, z = gvalues_xy.T cmap = get_cmap(el_cmap) elif element["type"] == "repeat_cell": cbar_title = "{0} ({1})".format(element["name"], "nuclei") centre = np.asarray(element['centre'], dtype=float) v1 = np.asarray(element['cell_vectors']['a']) v2 = np.asarray(element['cell_vectors']['b']) v3 = np.asarray(element['cell_vectors']['c']) bbox_pts = np.asarray([ np.array([0.0, 0.0, 0.0]), v1, v2, v3, v1 + v2, v1 + v3, v1 + v2 + v3, v2 + v3 ]) bbox_x, bbox_y, bbox_z = bbox_pts.T xmin, xmax, ymin, ymax, zmin, zmax = (bbox_x.min(), bbox_x.max(), bbox_y.min(), bbox_y.max(), bbox_z.min(), bbox_z.max() ) # l,r,bottom,top xmin, ymin, ymin = np.array( (xmin, ymin, ymin)) - 0.5 * (v1 + v2 + v3) + np.array(centre) xmax, ymax, zmax = np.array( (xmax, ymax, zmax)) - 0.5 * (v1 + v2 + v3) + np.array(centre) corners, corners_xy, gpoints, gpoints_xy = sliceplane_points( (xmin, xmax, ymin, ymax, zmin, zmax), scentre, snormal, cell_size, orientation, alter_bbox, angle_step, dist_tol) gvalues = np.full((gpoints_xy.shape[0], ), 0, dtype=np.float64) # create a map of site labels to color and index color_map = {(d[0], d[1]): i + 1 for i, d in enumerate( sorted( set([(site["label"], site["color_fill"]) for site in element["sites"]])))} for site in element["sites"]: mask = np.abs(np.linalg.norm(gpoints - site["ccoord"], axis=1)) < site["radius"] gvalues[mask] = color_map[(site["label"], site["color_fill"])] x, y = gpoints_xy.T z = gvalues # make cmap be correct for color_map v2colmap = {v: k[1] for k, v in color_map.items()} clist = ["white"] + [v2colmap[k] for k in sorted(v2colmap.keys())] cmap = LinearSegmentedColormap.from_list("cmap_name", clist, N=len(clist)) else: continue el_vmin = np.nanmin(z) if el_vmin is None else el_vmin el_vmax = np.nanmax(z) if el_vmax is None else el_vmax cbar_fmt = ticker.FuncFormatter(fmt_scientific) min_exp, min_diff_exp = (2, 2) exp_min, exp_max = int('{:.2e}'.format(el_vmin).split('e')[1]), int( '{:.2e}'.format(el_vmax).split('e')[1]) if abs(exp_min - exp_max) < min_diff_exp and abs(exp_min) > min_exp: el_multiplier = 10**float(exp_min) el_vmin /= el_multiplier el_vmax /= el_multiplier z /= el_multiplier cbar_title += r" $\times 10^{{{}}}$".format(int(exp_min)) x_axis, x_arr = np.unique(x, return_inverse=True) y_axis, y_arr = np.unique(y, return_inverse=True) z_array = np.full((np.max(y_arr) + 1, np.max(x_arr) + 1), np.nan) z_array[y_arr, x_arr] = z print("plotting contour") if el_contourf: cset = ax.contourf(x_axis, y_axis, z_array, cmap=cmap, vmin=el_vmin, vmax=el_vmax, extend='both') else: cset = ax.contour(x_axis, y_axis, z_array, cmap=cmap, vmin=el_vmin, vmax=el_vmax, extend='both') norm = Normalize(vmin=el_vmin, vmax=el_vmax) divider = make_axes_locatable(ax) cax = divider.append_axes('bottom', size='5%', pad=0.3) # see https://matplotlib.org/devdocs/tutorials/colors/colorbar_only.html cbar = ColorbarBase(cax, cmap=cmap, norm=norm, orientation="horizontal", ticklocation="bottom", extend="both", format=cbar_fmt) cbar.set_label(cbar_title, fontsize=8) if element["type"] == "repeat_cell": v2labelmap = {v: k[0] for k, v in color_map.items()} cbar.set_ticks(sorted(v2labelmap.keys())) cbar.set_ticklabels( [v2labelmap[k] for k in sorted(v2labelmap.keys())]) cax.tick_params(labelsize=8) for tick in cax.get_xticklabels(): tick.set_rotation(cbar_tick_rot) if el_corners: crnrs = [c for c in zip(corners_xy, corners)] for cxy, c3d in [crnrs[2], crnrs[0], crnrs[3], crnrs[1]]: ax.scatter([cxy[0]], [cxy[1]], label="({0:.2f}, {1:.2f}, {2:.2f})".format(*c3d), edgecolor='black') # ax.legend(ncol=1, loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize="x-small", # title="Coordinate\nMapping") ax.legend(ncol=2, loc='lower center', fontsize="x-small", bbox_to_anchor=(0.5, 1.0), title="Coordinate Mapping", framealpha=0.5) final_axes.append((ax, cax)) return fig, final_axes
def Plot(): """ Basic usage: `PlotLHA --help` Requires a YAML config file that specifies at least the `'scatterplot'` dict with the list '`plots`'. * Automatically uses the `'latex'` attribute of specified LHA blocks for labels. * Fields for x/y/z axes can be specified by either `BLOCKNAME.values.LHAID` or the specified `'parameter'` attribute. * New fields to plot can be computed using existing fields * Optional constraints on the different fields may be specified * Various options can be passed to `matplotlib`s `legend`, `scatter`, `colorbar` functions. * Optional ticks can be set manually. __Example config.yml__ --- scatterplot: conf: datafile: "mssm.h5" newfields: TanBeta: "DATA['HMIX.values.2'].apply(abs).apply(tan)" constraints: - "PDATA['TREELEVELUNITARITYwTRILINEARS.values.1']<0.5" # enforces e.g. unitarity plots: - filename: "mssm_TanBetaMSUSYmH.png" # one scatterplot y-axis: {field: TanBeta, label: '$\\tan\\beta$'} x-axis: field: MSUSY label: "$m_{SUSY}$ (TeV)$" lognorm: True ticks: - [1000,2000,3000,4000] - ['$1$','$2','$3','$4$'] z-axis: field: MASS.values.25 colorbar: True label: "$m_h$ (GeV)" alpha: 0.8 textbox: {x: 0.9, y: 0.3, text: 'some info'} - filename: "mssm_mhiggs.png" # multiple lines in one plot with legend constraints: [] # ignore all global constraints x-axis: field: MSUSY, label: 'Massparameter (GeV)' y-axis: lognorm: True, label: '$m_{SUSY}$ (GeV)' plots: - y-axis: MASS.values.25 color: red label: '$m_{h_1}$' - y-axis: MASS.values.26 color: green label: '$m_{h_2}$' - y-axis: MASS.values.35 color: blue label: '$m_{A}$' """ parser = ArgumentParser(description='Plot ScanLHA results.') parser.add_argument( "config", type=str, help= "path to YAML file config.yml containing the plot (and optional scan) config." ) parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity") args = parser.parse_args() logging.getLogger().setLevel(logging.INFO) if args.verbose: logging.getLogger().setLevel(logging.DEBUG) c = Config(args.config) DIR = os.path.dirname(os.path.abspath(args.config)) + '/' if 'scatterplot' not in c: logging.error('config file must contain "scatterplot" dict.') exit(1) if 'plots' not in c['scatterplot']: logging.error('no plots to plot') exit(1) conf = PlotConf() conf = conf.new_child(c['scatterplot'].get('conf', {})) if not os.path.isfile(conf['datafile']): logging.error('Data file {} does not exist.'.format(conf['datafile'])) exit(1) store = HDFStore(conf['datafile']) path = 'results' # TODO DATA = store[path] attrs = store.get_storer(path).attrs if hasattr(attrs, 'config') and conf.get('conf_overwrite', False): attrs.config['scatterplot'] = {} c.append(attrs.config) if not DATA.empty and 'newfields' in conf: for field, expr in conf['newfields'].items(): logging.debug("executing DATA[{}] = {}]".format(field, expr)) DATA[field] = eval(expr) logging.debug("done.") pcount = 0 for p in c['scatterplot']['plots']: lcount = 0 pconf = conf.new_child(p) plt.cla() plt.clf() plt.rcParams.update(pconf['rcParams']) if pconf['fontsize'] != conf['fontsize']: plt.rcParams.update({'font.size': pconf['fontsize']}) if pconf['colorbar_only']: plt.figure(figsize=(8, 0.25)) ax = plt.gca() norm = Normalize(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) if pconf['z-axis']['lognorm']: norm = LogNorm(vmin=pconf['z-axis']['vmin'], vmax=pconf['z-axis']['vmax']) cbar = ColorbarBase( ax, norm=norm, cmap=pconf['cmap'], orientation=pconf['z-axis']['colorbar_orientation']) if pconf['z-axis']['colorbar_orientation'] == 'horizontal': ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') if pconf['z-axis']['label']: cbar.set_label(pconf['z-axis']['label']) if pconf['z-axis']['ticks']: cbar.set_ticks(pconf['z-axis']['ticks']) plt.savefig(pconf['filename'], bbox_inches='tight') plt.figure() continue if pconf['title']: plt.title(conf['title']) if 'plots' not in p: p['plots'] = [p] for l in p['plots']: lconf = pconf.new_child(l) label = lconf['label'] label = label if label else None cmap = lconf['cmap'] zorder = lconf.get('zorder', lcount) color = lconf.get('color', "C{}".format(lcount)) x = lconf.get('x-field', lconf['x-axis'].get('field', None)) y = lconf.get('y-field', lconf['y-axis'].get('field', None)) z = lconf.get('z-field', lconf['z-axis'].get('field', None)) xlabel = lconf['x-axis']['label'] ylabel = lconf['y-axis']['label'] zlabel = lconf['z-axis']['label'] if hasattr(c, 'parameters'): xlabel = c.parameters.get( x, {'latex': xlabel})['latex'] if not xlabel else xlabel ylabel = c.parameters.get( y, {'latex': ylabel})['latex'] if not ylabel else ylabel zlabel = c.parameters.get( z, {'latex': zlabel})['latex'] if not zlabel else zlabel if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) if lconf['hline']: plt.axhline(y=y, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if lconf['vline']: plt.axvline(x=x, color=color, linestyle='-', lw=lconf['lw'], label=label, zorder=zorder, alpha=lconf['alpha']) continue if hasattr(c, 'parameters'): x = c.parameters.get(x, {'lha': x})['lha'] y = c.parameters.get(y, {'lha': y})['lha'] z = c.parameters.get(z, {'lha': z})['lha'] PDATA = DATA if (lconf['datafile'] and lconf['datafile'] != conf['datafile']): conf['datafile'] = lconf['datafile'] # TODO DATA = HDFStore(lconf['datafile'])['results'] # TODO PDATA = DATA if not PDATA.empty and 'newfields' in conf: for field, expr in conf['newfields'].items(): logging.debug("executing PATA[{}] = {}]".format( field, expr)) PDATA[field] = eval(expr) logging.debug("done.") for ax, field in {'x-axis': x, 'y-axis': y, 'z-axis': z}.items(): bounds = lconf[ax]['boundaries'] if len(bounds) == 2: PDATA = PDATA[(PDATA[field] >= bounds[0]) & (PDATA[field] <= bounds[1])] for constr in lconf['constraints']: PDATA = PDATA[eval(constr)] if lconf['x-axis']['lognorm']: plt.xscale('log') if lconf['y-axis']['lognorm']: plt.yscale('log') if z: color = PDATA[z] vmin = PDATA[z].min( ) if not lconf['z-axis']['vmin'] else lconf['z-axis']['vmin'] vmax = PDATA[z].max( ) if not lconf['z-axis']['vmax'] else lconf['z-axis']['vmax'] else: vmin = None vmax = None znorm = LogNorm(vmin=vmin, vmax=vmax) if lconf['z-axis']['lognorm'] else None cs = plt.scatter(PDATA[x], PDATA[y], zorder=zorder, label=label, cmap=cmap, c=color, vmin=vmin, vmax=vmax, norm=znorm, s=lconf['s'], alpha=lconf['alpha']) plt.margins(x=0.01, y=0.01) # TODO if lconf['x-axis']['ticks']: plt.xticks(lconf['x-axis']['ticks'][0], lconf['x-axis']['ticks'][1]) if lconf['y-axis']['ticks']: plt.yticks(lconf['y-axis']['ticks'][0], lconf['y-axis']['ticks'][1]) if lconf['z-axis']['colorbar']: cbar = plt.colorbar( cs, orientation=lconf['z-axis']['colorbar_orientation']) if zlabel: cbar.set_label(zlabel) if lconf['z-axis']['ticks']: cbar.set_ticks(lconf['z-axis']['ticks']) lcount += 1 if any([l.get('label', False) for l in p['plots']]): plt.legend(**pconf['legend']) if pconf['textbox'] and 'text' in pconf['textbox']: bbox = pconf['textbox'].get( 'bbox', dict(boxstyle='round', facecolor='white', alpha=0.2)) va = pconf['textbox'].get('va', 'top') ha = pconf['textbox'].get('ha', 'left') textsize = pconf['textbox'].get( 'fontsize', pconf['rcParams'].get('font.size', 15)) xtext = pconf['textbox'].get('x', 0.95) ytext = pconf['textbox'].get('y', 0.85) plt.gcf().text(xtext, ytext, pconf['textbox']['text'], fontsize=textsize, va=va, ha=ha, bbox=bbox) plotfile = DIR + p.get('filename', 'plot{}.png'.format(pcount)) logging.info("Saving {}.".format(plotfile)) plt.savefig(plotfile, bbox_inches="tight", dpi=pconf['dpi']) pcount += 1 store.close()
def sign_plot(x, g=None, flat=False, labels=True, cmap=None, cbar_ax_bbox=None, ax=None, **kwargs): """ Significance plot, a heatmap of p values (based on Seaborn). Parameters ---------- x : array_like, ndarray or DataFrame If flat is False (default), x must be an array, any object exposing the array interface, containing p values. If flat is True, x must be a sign_array (returned by `scikit_posthocs.sign_array` function) g : array_like or ndarray, optional An array, any object exposing the array interface, containing group names. flat : bool, optional If `flat` is True, plots a significance array as a heatmap using seaborn. If `flat` is False (default), plots an array of p values. Non-flat mode is useful if you need to differentiate significance levels visually. It is the preferred mode. labels : bool, optional Plot axes labels (default) or not. cmap : list, optional 1) If flat is False (default): List consisting of five elements, that will be exported to ListedColormap method of matplotlib. First is for diagonal elements, second is for non-significant elements, third is for p < 0.001, fourth is for p < 0.01, fifth is for p < 0.05. 2) If flat is True: List consisting of three elements, that will be exported to ListedColormap method of matplotlib. First is for diagonal elements, second is for non-significant elements, third is for significant ones. 3) If not defined, default colormaps will be used. cbar_ax_bbox : list, optional Colorbar axes position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. Refer to `matplotlib.figure.Figure.add_axes` for more information. Default is [0.95, 0.35, 0.04, 0.3]. ax : matplotlib Axes, optional Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments Keyword arguments to be passed to seaborn heatmap method. These keyword args cannot be used: cbar, vmin, vmax, center. Returns ------- Axes object with the heatmap (and ColorBase object of cbar if `flat` is set to False). Examples -------- >>> x = np.array([[-1, 1, 1], [ 1, -1, 0], [ 1, 0, -1]]) >>> ph.sign_plot(x, flat = True) """ for key in ['cbar', 'vmin', 'vmax', 'center']: if key in kwargs: del kwargs[key] if isinstance(x, DataFrame): df = x.copy() else: x = np.array(x) g = g or np.arange(x.shape[0]) df = DataFrame(x, index=g, columns=g) dtype = df.values.dtype if not np.issubdtype(dtype, np.integer) and flat: raise ValueError( "X should be a sign_array or DataFrame of integer values") elif not np.issubdtype(dtype, np.floating) and not flat: raise ValueError("X should be an array or DataFrame of float p values") if not cmap and flat: # format: diagonal, non-significant, significant cmap = ['1', '#fbd7d4', '#1a9641'] elif not cmap and not flat: # format: diagonal, non-significant, p<0.001, p<0.01, p<0.05 cmap = ['1', '#fbd7d4', '#005a32', '#238b45', '#a1d99b'] if flat: g = heatmap(df, vmin=-1, vmax=1, cmap=ListedColormap(cmap), cbar=False, ax=ax, **kwargs) if not labels: g.set_xlabel('') g.set_ylabel('') return g else: df[(x <= 0.001) & (x >= 0)] = 1 df[(x <= 0.01) & (x > 0.001)] = 2 df[(x <= 0.05) & (x > 0.01)] = 3 df[(x > 0.05)] = 0 np.fill_diagonal(df.values, -1) if len(cmap) != 5: raise ValueError("Cmap list must contain 5 items") g = heatmap(df, vmin=-1, vmax=3, cmap=ListedColormap(cmap), center=1, cbar=False, ax=ax, **kwargs) if not labels: g.set_xlabel('') g.set_ylabel('') cbar_ax = g.figure.add_axes(cbar_ax_bbox or [0.95, 0.35, 0.04, 0.3]) cbar = ColorbarBase(cbar_ax, cmap=ListedColormap(cmap[2:] + [cmap[1]]), boundaries=[0, 1, 2, 3, 4]) cbar.set_ticks(np.linspace(0.5, 3.5, 4)) cbar.set_ticklabels(['p < 0.001', 'p < 0.01', 'p < 0.05', 'NS']) cbar.outline.set_linewidth(1) cbar.outline.set_edgecolor('0.5') cbar.ax.tick_params(size=0) return g, cbar
def create_multipanel_plot(size, dpi, shape, layout, var_info, cmap, lims): fig = plt.figure(figsize=size, dpi=dpi) rings = [] # the rect parameter will be ignore as we will set axes_locator rect = (0.08, 0.08, 0.9, 0.9) nrow,ncol = shape # divide the axes rectangle into grid whose size is specified # by horiz * vert horiz = [Scaled(1.)] for i in range(ncol - 1): horiz.extend([Fixed(.2), Scaled(1.)]) vert = [Scaled(.1), Fixed(.35), Scaled(1.)] for i in range(nrow - 1): vert.extend([Fixed(.1), Scaled(1.)]) divider = Divider(fig, rect, horiz, vert, aspect=False) # ax0 = fig.add_axes(rect, label="0") # ax0.set_aspect('equal', 'datalim') # ax = [ax0] + [fig.add_axes(rect, label="%d"%i, sharex=ax0, sharey=ax0) # for i in range(1,6)] ax = [fig.add_axes(rect, label="%d"%i) for i in range(len(layout))] cax = [fig.add_axes(rect, label='cb%d'%i) for i in range(ncol)] for i,a in enumerate(ax): # a.set_axes_locator(divider.new_locator(nx=(i // nrow) * 2, # ny=((i%nrow) + 1) * 2)) a.set_axes_locator(divider.new_locator(nx=(i % ncol) * 2, ny=(nrow - (i // ncol)) * 2)) a.set_aspect('equal', 'datalim') for i,a in enumerate(cax): a.set_axes_locator(divider.new_locator(nx=2 * i, ny=0)) for num,(a,(data, label, var)) in enumerate(zip(ax, layout)): norm,ticks,units = var_info[var] ppi_plot(init_data.xlocs, init_data.ylocs, data, norm=norm, cmap=cmap, ax=a, rings=rings) # a.set_title('%s (%s)' % (moment, units)) if num >= ncol: a.set_xlabel('X Distance (km)') cbar = ColorbarBase(ax=cax[num%ncol], norm=norm, cmap=cmap, orientation='horizontal') cbar.set_label('%s (%s)' % (label, units)) cbar.set_ticks(ticks) else: a.xaxis.set_major_formatter(plt.NullFormatter()) if num % ncol == 0: a.set_ylabel('Y Distance (km)') else: a.yaxis.set_major_formatter(plt.NullFormatter()) if lims: a.xaxis.set_major_locator(plt.MultipleLocator(lims[0])) a.yaxis.set_major_locator(plt.MultipleLocator(lims[0])) a.set_xlim(*lims[1:3]) a.set_ylim(*lims[3:]) # loc = 2 is upper left. TODO: Should patch matplotlib to use # same strings as legend at = AnchoredText("%s)" % chr(97 + num), loc=2, prop=dict(size='large'), frameon=True) # at.patch.set_boxstyle("round, pad=0., rounding_size=0.2") a.add_artist(at) return fig
def change_cbar_text(cbar: ColorbarBase, tick: list, text: list): cbar.set_ticks(tick) cbar.set_ticklabels(text)
def main(traveltime=False, alerttime=False, blindzone=False, bzreduction=False, optimalbz=False, txt_fontsize=14): lonmin, lonmax, latmin, latmax = 2.5, 37.5, 35.0, 48.0 dlat = 2.0 dlon = 2.0 meridians = np.arange(2.0, 40, 4.0) parallels = np.arange(33, 48, 2.0) cmapname = 'RdBu_r' cmap = cm.get_cmap(cmapname) cmap.set_over('grey') extend = 'max' dlevel = 0.5 datadir = './data/' lbl_fontsize = 16 cb_label = [] if traveltime: vmin = 0. vmax = 15. # fout = 'plots/travel_time_maps_reakt.png' fout = 'plots/travel_time_maps_reakt.pdf' cb_label.append('P-wave travel time to %d stations [s]' % 6) cb_label.append('Approximate inter-station distance [km]') if alerttime: vmin = 10. vmax = 60. # fout = 'plots/alert_time_maps_reakt.png' fout = 'plots/alert_time_maps_reakt.pdf' cb_label.append('Initial alert time [s]') if blindzone: vmin = 10. vmax = 200. cb_int = 15 # fout = 'plots/blind_zone_maps_reakt.png' fout = 'plots/blind_zone_maps_reakt.pdf' cb_label.append('No-warning zone radius [km]') cb_label.append('Alert delay ($\Delta t_{alert}$) [s]') cb_label.append('Magnitude with positive EEW zone') if bzreduction: cmap = cm.get_cmap('RdBu') cmap.set_over('grey') vmin = 10 vmax = 200 cb_int = 15 # fout = 'plots/blind_zone_reduction_reakt.png' fout = 'plots/blind_zone_reduction_reakt.pdf' cb_label.append('Blind zone reduction [km]') cb_label.append('Alert delay reduction [s]') if optimalbz: vmin = 10 vmax = 200 cb_int = 15 # fout = 'plots/optimal_blind_zone_reakt.png' fout = 'plots/optimal_blind_zone_reakt.pdf' cb_label.append('Optimal no-warning zone radius [km]') cb_label.append('Optimal alert delay ($\Delta t_{alert}$) [s]') cb_label.append('Optimal magnitude with positive EEW zone') # get the damage zone, that is the zone for which intensity is >= 5.0 # for magnitudes >= 5.0 mags, dz = damage_zone() fig = plt.figure(figsize=(16, 7)) # without Iceland # fig = plt.figure(figsize=(10, 7)) ax = fig.add_axes([0.05, 0., .8, 1.0]) # setup albers equal area conic basemap # lat_1 is first standard parallel. # lat_2 is second standard parallel. # lon_0,lat_0 is central point. if True: m = Basemap(width=5000000, height=2300000, resolution='l', projection='aea', \ lat_1=35., lat_2=48, lon_0=20, lat_0=42, ax=ax) # without Iceland # m = Basemap(width=3000000, height=1800000, # resolution='l', projection='aea', \ # lat_1=35., lat_2=48, lon_0=20, lat_0=42, ax=ax) m.drawmeridians(meridians, labels=[0, 0, 0, 1], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) m.drawparallels(parallels, labels=[1, 0, 0, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) m.drawcoastlines(zorder=2) m.drawcountries(linewidth=1.0, zorder=2) m.fillcontinents('lightgray', zorder=0) if traveltime: # plot Romanian data resultsfn = os.path.join(datadir, 'ptt_ro_6stations.npz') plot_ptt(resultsfn, m, cmap, dlevel, vmax=vmax) xtxt, ytxt = m(25.0, 48.8) ax.text(xtxt, ytxt, 'Romania', fontsize=txt_fontsize, horizontalalignment='center') # plot Greek data resultsfn = os.path.join(datadir, 'ptt_gr_6stations.npz') plot_ptt(resultsfn, m, cmap, dlevel, vmax=vmax) xtxt, ytxt = m(19.5, 36.5) ax.text(xtxt, ytxt, 'Greece', fontsize=txt_fontsize, horizontalalignment='center') # plot Swiss data resultsfn = os.path.join(datadir, 'ptt_ch_6stations.npz') plot_ptt(resultsfn, m, cmap, dlevel, vmax=vmax) xtxt, ytxt = m(8, 48.75) ax.text(xtxt, ytxt, 'Switzerland', fontsize=txt_fontsize, horizontalalignment='center') # plot Turkish data resultsfn = os.path.join(datadir, 'ptt_tr_6stations.npz') plot_ptt(resultsfn, m, cmap, dlevel, vmax=vmax) xtxt, ytxt = m(34.5, 39.5) ax.text(xtxt, ytxt, 'Turkey', fontsize=txt_fontsize, horizontalalignment='center') if alerttime or blindzone or bzreduction or optimalbz: if bzreduction or optimalbz: blindzone = True # plot Romanian data resultsfn = os.path.join(datadir, 'event_list_ro.csv') optbz = os.path.join(datadir, 'optimal_blindzone_ro.npz') plot_at(resultsfn, m, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) # plot Greek data resultsfn = os.path.join(datadir, 'event_list_gr.csv') optbz = os.path.join(datadir, 'optimal_blindzone_gr.npz') plot_at(resultsfn, m, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) # plot Swiss data resultsfn = os.path.join(datadir, 'event_list_ch.csv') optbz = os.path.join(datadir, 'optimal_blindzone_ch.npz') plot_at(resultsfn, m, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) # plot Turkish data resultsfn = os.path.join(datadir, 'event_list_tr.csv') optbz = os.path.join(datadir, 'optimal_blindzone_tr.npz') plot_at(resultsfn, m, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) darkgray = (107 / 255., 107 / 255., 107 / 255.) # add a panel for California if True: # ax_cal = fig.add_axes([0.62, 0., .31, 1.0]) ax_cal = fig.add_axes([0.5, 0.53, .45, .35]) mca = Basemap(width=700000, height=750000, resolution='l', projection='aea', \ lat_1=31, lat_2=38., lon_0=-117.5, lat_0=34.5, ax=ax_cal) # mca = Basemap(projection='merc', llcrnrlat=31, urcrnrlat=37.5, # llcrnrlon=-121.5, urcrnrlon=-114, lat_ts=34.5, # resolution='i', ax=ax_cal) mca.drawcoastlines(zorder=2) mca.drawcountries(zorder=2) mca.drawstates(zorder=2) mca.fillcontinents(color=darkgray, zorder=0) mca.drawmeridians([-119, -115], labels=[0, 0, 1, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) mca.drawparallels([32, 34, 36], labels=[0, 1, 0, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) if traveltime: resultsfn = os.path.join(datadir, 'ptt_ca_6stations.npz') plot_ptt(resultsfn, mca, cmap, dlevel, vmin=vmin, vmax=vmax) xtxt, ytxt = mca(-121.25, 37.3) ax_cal.text(xtxt, ytxt, 'southern California', fontsize=txt_fontsize, bbox=dict(facecolor='#eeeeee', alpha=1.0)) if alerttime or blindzone or optimalbz: if bzreduction or optimalbz: blindzone = True resultsfn = os.path.join(datadir, 'event_list_ca.csv') optbz = os.path.join(datadir, 'optimal_blindzone_ca.npz') plot_at(resultsfn, mca, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz, ssize=50) # Create an inset for Iceland if True: ax_ice = fig.add_axes([0.05, 0.63, .2, .25]) mi = Basemap(width=550000, height=580000, resolution='l', projection='aea', \ lat_1=62.5, lat_2=68.5, lon_0=-19, lat_0=65, ax=ax_ice) mi.drawcoastlines(zorder=2) mi.fillcontinents(color=darkgray, zorder=0) mi.drawmeridians(np.arange(-26, -12, 5), labels=[0, 0, 1, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) mi.drawparallels(np.arange(60, 70, 2), labels=[0, 1, 0, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) # plot Iceland data if traveltime: resultsfn = os.path.join(datadir, 'ptt_is_6stations.npz') plot_ptt(resultsfn, mi, cmap, dlevel, vmin=vmin, vmax=vmax) xtxt, ytxt = mi(-23.5, 67) ax_ice.text(xtxt, ytxt, 'Iceland', fontsize=txt_fontsize) if alerttime or blindzone or optimalbz: if bzreduction or optimalbz: blindzone = True resultsfn = os.path.join(datadir, 'event_list_iceland_all.csv') optbz = os.path.join(datadir, 'optimal_blindzone_is.npz') plot_at(resultsfn, mi, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) # Create an inset for New Zealand if True: ax_nz = fig.add_axes([-0.04, 0.12, .5, .45]) mnz = Basemap(width=1300000, height=1700000, resolution='l', projection='aea', \ lat_1=-50., lat_2=-32, lon_0=172, lat_0=-41, ax=ax_nz) mnz.drawcoastlines(zorder=2) mnz.fillcontinents(color=darkgray, zorder=0) mnz.drawmeridians(np.arange(164, 182, 6), labels=[0, 0, 0, 1], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) mnz.drawparallels(np.arange(-51, -31, 2), labels=[1, 0, 0, 0], color='lightgray', linewidth=0.5, zorder=0, fontsize=lbl_fontsize) # plot NZ data if traveltime: resultsfn = os.path.join(datadir, 'ptt_nz_6stations.npz') plot_ptt(resultsfn, mnz, cmap, dlevel, vmin=vmin, vmax=vmax) xtxt, ytxt = mnz(165.5, -37) ax_nz.text(xtxt, ytxt, 'New Zealand', fontsize=txt_fontsize) if alerttime or blindzone or optimalbz: if bzreduction or optimalbz: blindzone = True resultsfn = os.path.join(datadir, 'event_list_nz.csv') optbz = os.path.join(datadir, 'optimal_blindzone_nz.npz') plot_at(resultsfn, mnz, cmap, vmin=vmin, vmax=vmax, blindzone=blindzone, optbz=optbz, bzreduction=bzreduction, optimalbz=optimalbz) cb_fontsize = 14 lbl_fontsize = 14 lbl_pad = 10 cax = fig.add_axes([0.87, 0.1, 0.01, 0.8]) if traveltime: cb = ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) cb.set_label(cb_label[0], fontsize=cb_fontsize, labelpad=lbl_pad) cb.ax.tick_params(labelsize=lbl_fontsize) cax2 = fig.add_axes([.95, 0.1, 0.01, 0.8]) cb2 = ColorbarBase(cax2, cmap=cmap, norm=Normalize(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) cb2.set_label(cb_label[1], fontsize=cb_fontsize, labelpad=lbl_pad) cb2.set_ticks(np.arange(1.5, 16.5, 1.5)) cb2.set_ticklabels(station_distance(np.arange(1.5, 16.5, 1.5), 8.0, 6.5, 6)) cb2.ax.tick_params(labelsize=lbl_fontsize) if (blindzone or optimalbz) and not bzreduction: cb = ColorbarBase(cax, cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) ticks = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200]) cb.set_ticks(ticks) cb.set_ticklabels(ticks) cb.set_label(cb_label[0], fontsize=cb_fontsize, labelpad=lbl_pad) cb.ax.tick_params(labelsize=lbl_fontsize) cax2 = fig.add_axes([0.95, 0.1, 0.01, 0.8]) cax3 = fig.add_axes([1.03, 0.1, 0.01, 0.8]) cb2 = ColorbarBase(cax2, cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) cb2.set_label(cb_label[1], fontsize=cb_fontsize, labelpad=lbl_pad) cb2.set_ticks(ticks) cb2.set_ticklabels([int(x / 3.5 + 0.5) for x in ticks]) cb2.ax.tick_params(labelsize=lbl_fontsize) cb3 = ColorbarBase(cax3, cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) tklbl = [] for _bz in ticks: idx = np.argmin(np.abs(dz - np.sqrt(_bz * _bz + 64))) tklbl.append(mags[idx]) cb3.set_label(cb_label[2], fontsize=cb_fontsize, labelpad=lbl_pad) cb3.set_ticks(ticks) cb3.set_ticklabels(tklbl) cb3.ax.tick_params(labelsize=lbl_fontsize) if bzreduction: cb = ColorbarBase(cax, cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) ticks = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200]) cb.set_ticks(ticks) cb.set_ticklabels(ticks) cb.set_label(cb_label[0], fontsize=cb_fontsize, labelpad=lbl_pad) cb.ax.tick_params(labelsize=lbl_fontsize) cax2 = fig.add_axes([.95, 0.1, 0.01, 0.8]) cb2 = ColorbarBase(cax2, cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax), orientation='vertical', extend=extend) cb2.set_label(cb_label[1], fontsize=cb_fontsize, labelpad=lbl_pad) cb2.set_ticks(ticks) cb2.set_ticklabels([int(x / 6.5 + 0.5) for x in ticks]) cb2.ax.tick_params(labelsize=lbl_fontsize) fig.savefig(fout, bbox_inches='tight') plt.show()