def save_bokeh(self, filename): # Instantiate the figure f = bk_plt.figure() # Plot each line to bokeh for line in self.lines: f.line(line[0], line[1], line_color=line[2]) # Plot the text to bokeh for text in self.texts: f.add_layout(bk_mod.Label(x=text[0], y=text[1], text=text[2])) # Save the results bk_io.export_png(f, filename)
def show_bokeh(self): # Instantiate the figure f = bk_plt.figure() # Plot each line to bokeh for line in self.lines: f.line(line[0], line[1], line_color=line[2]) # Plot the text to bokeh for text in self.texts: f.add_layout(bk_mod.Label(x=text[0], y=text[1], text=text[2])) # Show the results bk_plt.show(f)
def plot_error_large(): fig = bpl.figure(plot_width=800, plot_height=500, toolbar_location=None) error_text = mpl.Label(x=400, y=250, x_units='screen', y_units='screen', text='An error occured when trying to plot this dataset!', text_color='red', text_align='center') fig.add_layout(error_text) return fig
def plot_error(width, height): fig = bpl.figure(plot_width=width, plot_height=height, toolbar_location=None) error_text = mpl.Label(x=width/2., y=height/2., x_units='screen', y_units='screen', text='An error occured when trying to plot this dataset!', text_color='red', text_align='center') fig.add_layout(error_text) return fig
def plot_generic_OC(datafile): hdf = h5py.File(datafile, 'r') TOOLS = "pan, box_zoom, wheel_zoom, reset" xscale = get_attr(hdf['O-C'], 'xscale', default='linear') if 'O-C' in hdf else 'linear' yscale = get_attr(hdf['O-C'], 'yscale', default='linear') if 'O-C' in hdf else 'linear' fig = bpl.figure(plot_width=800, plot_height=200, toolbar_location='right', tools=TOOLS, x_axis_type=xscale, y_axis_type=yscale) colors = ['red', 'blue', 'green'] #-- plot the O-C if 'O-C' in hdf: models = hdf['O-C'] for i, (name, dataset) in enumerate(models.items()): xpar = get_attr(dataset, 'xpar', 'x') ypar = get_attr(dataset, 'ypar', 'y') if get_attr(dataset, 'datatype', None) == 'continuous': fig.line(dataset[xpar], dataset[ypar], color=colors[i], legend=name) elif get_attr(dataset, 'datatype', None) == 'discrete': fig.circle(dataset[xpar], dataset[ypar], color=colors[i], legend=name, size=7) plot_errorbars(fig, dataset[xpar], dataset[ypar], dataset[ypar+'_err'], line_width=1, color=colors[i]) hline = mpl.Span(location=0, dimension='width', line_color='black', line_width=2, line_dash='dashed') fig.add_layout(hline) fig.yaxis.axis_label = get_attr(models, 'ylabel', 'y') fig.xaxis.axis_label = get_attr(models, 'xlabel', 'x') else: error_text = mpl.Label(x=400, y=100, x_units='screen', y_units='screen', text='No O-C data available.', text_color='red', text_align='center') fig.add_layout(error_text) fig.toolbar.logo=None fig.yaxis.axis_label_text_font_size = '10pt' fig.xaxis.axis_label_text_font_size = '10pt' fig.min_border = 5 hdf.close() return fig
def text(x, y, s, color='gray', size='8pt', hold=False): """Add text annotation to a plot. :param x: x location of left of text :param y: y location of bottom of text :param s: text to add :param color: text color (see `Bokeh colors`_) :param size: text size (e.g. '12pt', '3em') :param hold: if set to True, output is not plotted immediately, but combined with the next plot >>> import arlpy.plot >>> arlpy.plot.plot([0, 20], [0, 10], hold=True) >>> arlpy.plot.text(7, 3, 'demo', color='orange') """ global _figure if _figure is None: return _figure.add_layout( _bmodels.Label(x=x, y=y, text=s, text_font_size=size, text_color=color)) if not hold and not _hold: _show(_figure) _figure = None
def plot_visibility(observation): """ Plot airmass and moondistance on the night of observations """ fig = bpl.figure(plot_width=400, plot_height=240, toolbar_location=None, y_range=(0, 90), x_axis_type="datetime") fig.toolbar.logo = None fig.title.align = 'center' fig.yaxis.axis_label = 'Altitude (dgr)' fig.xaxis.axis_label = 'UT' fig.yaxis.axis_label_text_font_size = '10pt' fig.xaxis.axis_label_text_font_size = '10pt' fig.min_border = 5 try: if observation.observatory.space_craft: label = mpl.Label(x=180, y=110, x_units='screen', y_units='screen', text='Observatory is a Space Craft', render_mode='css', border_line_color='red', border_line_alpha=1.0, text_color='red', text_align='center', text_baseline='middle', background_fill_color='white', background_fill_alpha=1.0) fig.add_layout(label) return fig observatory = observation.observatory.get_EarthLocation() time = Time(observation.hjd, format='jd') sunset, sunrise = observation.observatory.get_sunset_sunrise(time) times = np.linspace(sunset.jd, sunrise.jd, 100) times = Time(times, format='jd') star = SkyCoord( ra=observation.ra * u.deg, dec=observation.dec * u.deg, ) frame_star = AltAz(obstime=times, location=observatory) star_altaz = star.transform_to(frame_star) moon = get_moon(times) moon_altaz = moon.transform_to(frame_star) times = times.to_datetime() fig.line(times, star_altaz.alt, color='blue', line_width=2) fig.line(times, moon_altaz.alt, color='orange', line_dash='dashed', line_width=2) obsstart = (time - observation.exptime / 2 * u.second).to_datetime() obsend = (time + observation.exptime / 2 * u.second).to_datetime() obs = mpl.BoxAnnotation(left=obsstart, right=obsend, fill_alpha=0.5, fill_color='red') fig.add_layout(obs) except Exception as e: print(e) label = mpl.Label(x=75, y=40, x_units='screen', text='Could not calculate visibility', render_mode='css', border_line_color='red', border_line_alpha=1.0, text_color='red', background_fill_color='white', background_fill_alpha=1.0) fig.add_layout(label) return fig
def plot_lightcurve(lightcurve_id, period=None, binsize=0.01): lightcurve = LightCurve.objects.get(pk=lightcurve_id) time, flux, header = lightcurve.get_lightcurve() fig1 = bpl.figure(plot_width=1600, plot_height=400) #, sizing_mode='scale_width' fig1.line(time, flux, line_width=1, color="blue") fig1.toolbar.logo = None fig1.yaxis.axis_label = 'Flux' fig1.xaxis.axis_label = 'Time (TJD)' fig1.yaxis.axis_label_text_font_size = '10pt' fig1.xaxis.axis_label_text_font_size = '10pt' fig1.min_border = 5 fig2 = bpl.figure(plot_width=1600, plot_height=400) #, sizing_mode='scale_width' if not period is None: # calculate phase and sort on phase phase = time % period / period inds = phase.argsort() phase, flux = phase[inds], flux[inds] # rebin the phase light curve phase, flux = spectools.rebin_phased_lightcurve(phase, flux, binsize=binsize) phase = np.hstack([phase, phase + 1]) flux = np.hstack([flux, flux]) fig2.line(phase, flux, line_width=1, color="blue") else: label = mpl.Label( x=800, y=200, x_units='screen', y_units='screen', text='No period provided, cannot phase fold lightcurve', render_mode='css', text_align='center', border_line_color='red', border_line_alpha=1.0, text_color='red', background_fill_color='white', background_fill_alpha=1.0) fig2.add_layout(label) fig2.toolbar.logo = None fig2.yaxis.axis_label = 'Flux' fig2.xaxis.axis_label = 'Phase' fig2.yaxis.axis_label_text_font_size = '10pt' fig2.xaxis.axis_label_text_font_size = '10pt' fig2.min_border = 5 return fig1, fig2
def plot_spectrum(spectrum_id, rebin=1, normalize=True, porder=3): ''' Plot spectrum Parameters: ----------- spectrum_id ID of the spectrum rebin int() Bin size normalize bool() Normalize spectrum yes/no Returns: -------- tabs ''' # Load spectrum, individual spectra (specfiles), and instrument spectrum = Spectrum.objects.get(pk=spectrum_id) specfiles = spectrum.specfile_set.order_by('filetype') instrument = spectrum.instrument # Determine flux unit funit_str = spectrum.flux_units # Set flux unit if funit_str == 'ADU': funit = u.adu elif funit_str == 'ergs/cm/cm/s/A': funit = u.erg / u.cm / u.cm / u.s / u.AA else: funit = u.ct # Prepare list for tabs in the figure tabs = [] # Loop over spectra for specfile in specfiles: # Extract data wave, flux, header = specfile.get_spectrum() # Barycentric correction if not spectrum.barycor_bool: # Set value for barycenter correction barycor = spectrum.barycor # Apply barycenter correction wave = spectools.doppler_shift(wave, barycor) # Instrument specific settings if instrument == 'HERMES' or instrument == 'FEROS': # Restrict wavelength range sel = np.where(wave > 3860) wave, flux = wave[sel], flux[sel] # Rebin spectrum # If the spectrum is already normalized, set 'mean' to True to keep # the continuum at ~1. if spectrum.normalized: wave, flux = spectools.rebin_spectrum( wave, flux, binsize=rebin, mean=True, ) else: wave, flux = spectools.rebin_spectrum(wave, flux, binsize=rebin) ### # Normalize & merge spectra # Identify echelle spectra # -> wave is a np.ndarray of np.ndarrays if isinstance(wave[0], np.ndarray): # Set normalize to true if current value is 'None' if normalize == None: normalize = True # Normalize & merge spectra if normalize: # Prepare list for echelle orders orders = [] # Loop over each order for i, w in enumerate(wave): # Create Spectrum1D objects orders.append( Spectrum1D( spectral_axis=w * u.AA, flux=flux[i] * funit, )) # Normalize & merge spectra wave, flux = spectools.norm_merge_spectra(orders, order=porder) wave = wave.value # Set flux unit to 'normalized' funit_str = 'normalized' else: # Merge spectra wave, flux = spectools.merge_spectra(wave, flux) else: # Normalize & merge spectra if normalize: # Create Spectrum1D objects spec = Spectrum1D(spectral_axis=wave * u.AA, flux=flux * funit) # Normalize spectrum spec, std = spectools.norm_spectrum(spec, order=porder) # Split spectrum in 10 segments, # if standard deviation is too high if std > 0.05: nsegment = 10 nwave = len(wave) step = int(nwave / nsegment) segments = [] # Loop over segments i_old = 0 for i in range(step, step * nsegment, step): # Cut segments and add overlay range to the # segments, so that the normalization afterburner # can take effect overlap = int(step * 0.15) if i == step: flux_seg = flux[i_old:i + overlap] wave_seg = wave[i_old:i + overlap] elif i == nsegment - 1: flux_seg = flux[i_old - overlap:] wave_seg = wave[i_old - overlap:] else: flux_seg = flux[i_old - overlap:i + overlap] wave_seg = wave[i_old - overlap:i + overlap] i_old = i # Create Spectrum1D objects for the segments segments.append( Spectrum1D( spectral_axis=wave_seg * u.AA, flux=flux_seg * funit, )) # Normalize & merge spectra wave, flux = spectools.norm_merge_spectra( segments, order=porder, ) wave = wave.value else: wave = np.asarray(spec.spectral_axis) flux = np.asarray(spec.flux) # Set flux unit to 'normalized' funit_str = 'normalized' # Set the maximum and minimum so that weird peaks # are cut off automatically. fsort = np.sort(flux)[::-1] maxf = fsort[int(np.floor(len(flux) / 100.))] * 1.2 minf = np.max([np.min(flux) * 0.95, 0]) # Initialize figure #, sizing_mode='scale_width' fig = bpl.figure(plot_width=1550, plot_height=400, y_range=[minf, maxf]) # Plot spectrum fig.line(wave, flux, line_width=1, color="blue") # Annotate He and H lines # Define lines: Lines = [ (3204.11, 'darkblue', 'HeII'), (3835.39, 'red', 'Hη'), (3888.05, 'red', 'Hζ'), (3970.07, 'red', 'Hε'), (4103., 'red', 'Hδ'), (4201., 'darkblue', 'HeII'), (4340.49, 'red', 'Hγ'), #(4339, 'darkblue', 'HeII'), (4471, 'blue', 'HeI'), (4542, 'darkblue', 'HeII'), (4687, 'darkblue', 'HeII'), (4861.36, 'red', 'Hβ'), (4922, 'blue', 'HeI'), (5412., 'darkblue', 'HeII'), (5877, 'blue', 'HeI'), (6562.1, 'red', 'Hα'), (6685, 'darkblue', 'HeII'), ] Annot = [] # For each line make an annotation box and and a label for h in Lines: # Restrict to lines in plot range if h[0] > wave[0] and h[0] < wave[-1]: # Make annotation Annot.append( mpl.BoxAnnotation(left=h[0] - 2, right=h[0] + 2, fill_alpha=0.3, fill_color=h[1])) # Make label lab = mpl.Label( x=h[0], y=345., y_units='screen', text=h[2], angle=90, angle_units='deg', text_align='right', text_color=h[1], text_alpha=0.6, text_font_size='14px', border_line_color='white', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=0.3, ) fig.add_layout(lab) # Render annotations fig.renderers.extend(Annot) # Set figure labels fig.toolbar.logo = None fig.yaxis.axis_label = 'Flux (' + funit_str + ')' fig.xaxis.axis_label = 'Wavelength (AA)' fig.yaxis.axis_label_text_font_size = '10pt' fig.xaxis.axis_label_text_font_size = '10pt' fig.min_border = 5 # Fill tabs list tabs.append(widgets.Panel(child=fig, title=specfile.filetype)) # Make figure from tabs list tabs = widgets.Tabs(tabs=tabs) return tabs
def plot(x, y=None, fs=None, maxpts=10000, pooling=None, color=None, style='solid', thickness=1, marker=None, filled=False, size=6, mskip=0, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, xtype='auto', ytype='auto', width=None, height=None, legend=None, hold=False, interactive=None): """Plot a line graph or time series. :param x: x data or time series data (if y is None) :param y: y data or None (if time series) :param fs: sampling rate for time series data :param maxpts: maximum number of points to plot (downsampled if more points provided) :param pooling: pooling for downsampling (None, 'max', 'min', 'mean', 'median') :param color: line color (see `Bokeh colors <https://bokeh.pydata.org/en/latest/docs/reference/colors.html>`_) :param style: line style ('solid', 'dashed', 'dotted', 'dotdash', 'dashdot', None) :param thickness: line width in pixels :param marker: point markers ('.', 'o', 's', '*', 'x', '+', 'd', '^') :param filled: filled markers or outlined ones :param size: marker size :param mskip: number of points to skip marking (to avoid too many markers) :param title: figure title :param xlabel: x-axis label :param ylabel: y-axis label :param xlim: x-axis limits (min, max) :param ylim: y-axis limits (min, max) :param xtype: x-axis type ('auto', 'linear', 'log', etc) :param ytype: y-axis type ('auto', 'linear', 'log', etc) :param width: figure width in pixels :param height: figure height in pixels :param legend: legend text :param interactive: enable interactive tools (pan, zoom, etc) for plot :param hold: if set to True, output is not plotted immediately, but combined with the next plot >>> import arlpy.plot >>> import numpy as np >>> arlpy.plot.plot([0,10], [1,-1], color='blue', marker='o', filled=True, legend='A', hold=True) >>> arlpy.plot.plot(np.random.normal(size=1000), fs=100, color='green', legend='B') """ global _figure, _color x = _np.array(x, ndmin=1, dtype=_np.float, copy=False) if y is None: y = x x = _np.arange(x.size) if fs is not None: x = x / fs if xlabel is None: xlabel = 'Time (s)' if xlim is None: xlim = (x[0], x[-1]) else: y = _np.array(y, ndmin=1, dtype=_np.float, copy=False) if _figure is None: _figure = _new_figure(title, width, height, xlabel, ylabel, xlim, ylim, xtype, ytype, interactive) if color is None: color = _colors[_color % len(_colors)] _color += 1 if x.size > maxpts: n = int(_np.ceil(x.size / maxpts)) x = x[::n] desc = 'Downsampled by ' + str(n) if pooling is None: y = y[::n] elif pooling == 'max': desc += ', ' + pooling + ' pooled' y = _np.amax(_np.reshape(y[:n * (y.size // n)], (-1, n)), axis=1) elif pooling == 'min': desc += ', ' + pooling + ' pooled' y = _np.amin(_np.reshape(y[:n * (y.size // n)], (-1, n)), axis=1) elif pooling == 'mean': desc += ', ' + pooling + ' pooled' y = _np.mean(_np.reshape(y[:n * (y.size // n)], (-1, n)), axis=1) elif pooling == 'median': desc += ', ' + pooling + ' pooled' y = _np.mean(_np.reshape(y[:n * (y.size // n)], (-1, n)), axis=1) else: _warnings.warn('Unknown pooling: ' + pooling) y = y[::n] if len(x) > len(y): x = x[:len(y)] _figure.add_layout( _bmodels.Label(x=5, y=5, x_units='screen', y_units='screen', text=desc, text_font_size="8pt", text_alpha=0.5)) if style is not None: _figure.line(x, y, line_color=color, line_dash=style, line_width=thickness, legend=legend) if marker is not None: scatter(x[::(mskip + 1)], y[::(mskip + 1)], marker=marker, filled=filled, size=size, color=color, legend=legend, hold=True) if not hold and not _hold: _show(_figure) _figure = None
clr = pal[0] else: clr = pal[2] fig_cput.line(np.percentile(cputs[aidx, :, :], 50, axis=0) / np.percentile(cputs_full, 50, axis=0), np.percentile(Fs[aidx, :, :], 50, axis=0) / np.percentile(Fs[2, :, :], 50), line_color=clr, line_width=8, legend=anm) rndlbl = bkm.Label(x=1.0, x_offset=-10, y=700, y_units='screen', text='Full Dataset MCMC', angle=90, angle_units='deg', text_font_size='30pt') rndspan = bkm.Span(location=1.0, dimension='height', line_width=8, line_color='black', line_dash='40 40') fig_cput.add_layout(rndspan) fig_cput.add_layout(rndlbl) fig_cput.legend.label_text_font_size = legend_font_size fig_cput.legend.glyph_width = 40 fig_cput.legend.glyph_height = 80 fig_cput.legend.spacing = 20
def get_plot(inp_x, inp_y, inp_clr): """Returns a Bokeh plot of the input values, and a message with the number of COFs found.""" q_list = [config.quantities[label] for label in [inp_x, inp_y, inp_clr]] results_wnone = get_data_aiida(q_list) #returns *** # dump None lists that make bokeh crash results = [] for l in results_wnone: if None not in l: results.append(l) # prepare data for plotting nresults = len(results) if not results: results = [['x', 'x', 'x', 0, 0, 0]] msg = "No matching COFs found." else: msg = "{} COFs found.<br> <b>Click on any point for details!</b>".format(nresults) mat_id, mat_name, mat_class, x, y, clrs = zip(*results) # returned *** x = list(map(float, x)) y = list(map(float, y)) clrs = list(map(float, clrs)) data = {'x': x, 'y': y, 'color': clrs, 'mat_id': mat_id, 'mat_name': mat_name, 'mat_class': mat_class} # create bokeh plot source = bmd.ColumnDataSource(data=data) hover = bmd.HoverTool(tooltips=[]) tap = bmd.TapTool() p_new = bpl.figure( plot_height=600, plot_width=600, toolbar_location='above', tools=[ 'pan', 'wheel_zoom', 'box_zoom', 'save', 'reset', hover, tap, ], active_drag='box_zoom', output_backend='webgl', title='', # trick: title is used as the colorbar label title_location='right', x_axis_type=q_list[0]['scale'], y_axis_type=q_list[1]['scale'], ) p_new.title.align = 'center' p_new.title.text_font_size = '10pt' p_new.title.text_font_style = 'italic' update_legends(p_new, q_list, hover) tap.callback = bmd.OpenURL(url="detail?mat_id=@mat_id") # Plot vertical line for comparison with amine-based technology (PE=1MJ/kg) if inp_y == 'CO2 parasitic energy (coal)': hline = bmd.Span(location=1, dimension='width', line_dash='dashed', line_color='grey', line_width=3) p_new.add_layout(hline) hline_descr = bmd.Label(x=30, y=1, x_units='screen', text_color='grey', text='amine-based sep.') p_new.add_layout(hline_descr) cmap = bmd.LinearColorMapper(palette=Plasma256, low=min(clrs), high=max(clrs)) fill_color = {'field': 'color', 'transform': cmap} p_new.circle('x', 'y', size=10, source=source, fill_color=fill_color) cbar = bmd.ColorBar(color_mapper=cmap, location=(0, 0)) p_new.add_layout(cbar, 'right') return p_new, msg
def blot(gdata, args=(), figure=None, squeeze=False, streamline=False, quiver=False, contour=False, diverging=False, group=None, xscale=1.0, yscale=1.0, style=None, legend=True, labelPrefix='', xlabel=None, ylabel=None, title=None, logx=False, logy=False, logz=False, color=None, fixaspect=False, vmin=None, vmax=None, edgecolors=None, **kwargs): """Plots Gkeyll data Unifies the plotting across a wide range of Gkyl applications. Can be used for both 1D an 2D data. Uses a proper colormap by default. Args: """ #----------------------------------------------------------------- #-- Data Loading ------------------------------------------------- numDims = gdata.getNumDims(squeeze=True) if numDims > 2: raise Exception('Only 1D and 2D plots are currently supported') #end # Get the handles on the grid and values grid = gdata.getGrid() values = gdata.getValues() lower, upper = gdata.getBounds() cells = gdata.getNumCells() # Squeeze the data (get rid of "collapsed" dimensions) axLabel = ['z_0', 'z_1', 'z_2', 'z_3', 'z_4', 'z_5'] if len(grid) > numDims: idx = [] for d in range(len(grid)): if cells[d] <= 1: idx.append(d) #end #end if idx: grid = np.delete(grid, idx) lower = np.delete(lower, idx) upper = np.delete(upper, idx) cells = np.delete(cells, idx) axLabel = np.delete(axLabel, idx) values = np.squeeze(values, tuple(idx)) #end numComps = values.shape[-1] if streamline or quiver: step = 2 else: step = 1 #end idxComps = range(int(np.floor(numComps / step))) numComps = len(idxComps) if xscale != 1.0: axLabel[0] = axLabel[0] + r' $\times$ {:.3e}'.format(xscale) #end if numDims == 2 and yscale != 1.0: axLabel[1] = axLabel[1] + r' $\times$ {:.3e}'.format(yscale) #end sr = np.sqrt(numComps) #determine the number of rows and columns if sr == np.ceil(sr): numRows = int(sr) numCols = int(sr) elif np.ceil(sr) * np.floor(sr) >= numComps: numRows = int(np.floor(sr)) numCols = int(np.ceil(sr)) else: numRows = int(np.ceil(sr)) numCols = int(np.ceil(sr)) # Prepare the figure if figure is None: fig = [] if numDims == 1: tooltips = [(axLabel[0], "$x"), ("value", "$y") ] #getting tooltips ready for different dimensions else: if streamline or quiver: tooltips = None else: tooltips = [(axLabel[0], "$x"), (axLabel[1], "$y"), ("value", "@image")] #end #end for comp in idxComps: if logx and logy: fig.append( blt.figure(tooltips=tooltips, x_axis_type="log", y_axis_type="log", frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10)) elif logx: fig.append( blt.figure( tooltips=tooltips, x_axis_type="log", frame_height=int( 600.0 / numRows ), #adjust figures with the size based on the screen size frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10) ) #adjust spacings betweewn subplots to be aligned elif logy: fig.append( blt.figure(tooltips=tooltips, y_axis_type="log", frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10)) else: fig.append( blt.figure(tooltips=tooltips, frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=60, min_border_bottom=10)) #-- Preparing the Axes ------------------------------------------- for comp in idxComps: fig[comp].xaxis.minor_tick_line_color = None #deleting minor ticks fig[comp].yaxis.minor_tick_line_color = None fig[comp].xaxis.major_label_text_font_size = '12pt' #tick font size adjustment fig[comp].yaxis.major_label_text_font_size = '12pt' fig[comp].xaxis.axis_label_text_font_size = '12pt' #label font size adjustment fig[comp].yaxis.axis_label_text_font_size = '12pt' fig[comp].xaxis.formatter = bm.BasicTickFormatter( precision=1) #adjust floating numbers of ticks fig[comp].yaxis.formatter = bm.BasicTickFormatter(precision=1) if numDims != 1: if comp % numCols != 0: #hiding labels for unnecessary locations fig[comp].yaxis.major_label_text_font_size = '0pt' #end if comp < (numRows - 1) * numCols: fig[comp].xaxis.major_label_text_font_size = '0pt' #end #end if comp >= (numRows - 1) * numCols: if xlabel is None: fig[comp].xaxis.axis_label = axLabel[0] else: #if there is xlabel to be specified fig[comp].xaxis.axis_label = xlabel #end #end #end if comp % numCols == 0: if ylabel is None: if numDims == 2: fig[comp].yaxis.axis_label = axLabel[1] #end else: fig[comp].yaxis.axis_label = ylabel #end #end #end #-- Main Plotting Loop ------------------------------------------- for comp in idxComps: if len(idxComps) > 1: if labelPrefix == "": label = str(comp) else: label = '{:s}_c{:d}'.format(labelPrefix, comp) #end else: label = labelPrefix #end #end # Special plots if numDims == 1: x = 0.5 * (grid[0][1:] + grid[0][:-1]) fig[comp].line(x, values[..., comp], line_width=2, legend=label) elif numDims == 2: if contour: pass elif streamline: magnitude = np.sqrt(values[..., 2 * comp]**2 + values[..., 2 * comp + 1]**2) gridCC = _gridNodalToCellCentered(grid, cells) plt.subplots(numRows, numCols, sharex=True, sharey=True) strm = plt.streamplot( gridCC[0] * xscale, gridCC[1] * yscale, # make streamline plot by matplotlib first values[..., 2 * comp].transpose(), values[..., 2 * comp + 1].transpose(), color=magnitude.transpose(), linewidth=2) lines = strm.lines # get the line and color data of matplotlib streamline pathes = lines.get_paths() arr = lines.get_array().data points = np.stack([p.vertices.T for p in pathes], axis=0) X = points[:, 0, :].tolist() Y = points[:, 1, :].tolist() mapper = bt.linear_cmap(field_name="color", palette=bp.Inferno256, low=arr.min(), high=arr.max()) # use the data to create a multiline, use linear_map and palette to set the color of the lines: source = bm.ColumnDataSource(dict(x=X, y=Y, color=arr)) fig[comp].multi_line("x", "y", line_color=mapper, source=source, line_width=3) colormapper = bm.LinearColorMapper( palette='Inferno256', low=np.amin(magnitude.transpose()), high=np.amax(magnitude.transpose())) #adding a color bar color_bar = bm.ColorBar( color_mapper=colormapper, width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') elif quiver: gridCC = _gridNodalToCellCentered(grid, cells) x_range = gridCC[0] * xscale #setting x coordinates y_range = gridCC[1] * yscale #setting y coordinates dx = grid[0][1] - grid[0][0] dy = grid[1][1] - grid[1][0] freq = 7 v_x = values[..., 2 * comp].transpose() v_y = values[..., 2 * comp + 1].transpose() X, Y = np.meshgrid(x_range, y_range) speed = np.sqrt(v_x**2 + v_y**2) theta = np.arctan2(v_y * dy, v_x * dx) #arctan(y/x) maxSpeed = speed.max() x0 = X[::freq, ::freq].flatten() y0 = Y[::freq, ::freq].flatten() length = speed[::freq, ::freq].flatten() / maxSpeed angle = theta[::freq, ::freq].flatten() x1 = x0 + 0.9 * freq * dx * v_x[::freq, ::freq].flatten( ) / speed[::freq, ::freq].max() y1 = y0 + 0.9 * freq * dy * v_y[::freq, ::freq].flatten( ) / speed[::freq, ::freq].max() fig[comp].segment(x0, y0, x1, y1, color='black') #vector line fig[comp].triangle(x1, y1, size=4.0, angle=angle - np.pi / 2, color='black') #vector arrow elif diverging: gridCC = _gridNodalToCellCentered(grid, cells) vmax = np.abs(values[..., comp]).max() x_range = grid[0] * xscale #setting x coordinates y_range = grid[1] * yscale #setting y coordinates CmToRgb = (255 * cm.RdBu_r(range(256))).astype( 'int') #extract colors from maplotlib colormap RgbToHexa = [ bc.RGB(*tuple(rgb)).to_hex() for rgb in CmToRgb ] # convert RGB numbers into colormap hexacode string mapper = bm.LinearColorMapper(palette=RgbToHexa, low=-vmax, high=vmax) #adding a color bar fig[comp].image(image=[values[..., comp].transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=14, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') # Basic plots else: gridCC = _gridNodalToCellCentered(grid, cells) x_range = grid[0] * xscale #setting x coordinates y_range = grid[1] * yscale #setting y coordinates if logz: tmp = np.array(values[..., comp]) if vmin is not None or vmax is not None: for i in range(tmp.shape[0]): for j in range(tmp.shape[1]): if vmin and tmp[i, j] < vmin: tmp[i, j] = vmin #end if vmax and tmp[i, j] > vmax: tmp[i, j] = vmax #end #end if vmin is not None: vminTemp = vmin else: vminTemp = np.amin(values[..., comp]) #end if vmax is not None: vmaxTemp = vmax else: vmaxTemp = np.amax(values[..., comp]) #end mapper = bm.LogColorMapper(palette='Inferno256', low=vminTemp, high=vmaxTemp) fig[comp].image(image=[tmp.transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, #adding a colorbar width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1 ), #deleting unnecessary floating numbers ticker=bm.BasicTicker(), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') else: mapper = bm.LinearColorMapper(palette='Inferno256', low=np.amin(values[..., comp]), high=np.amax(values[..., comp])) fig[comp].image(image=[values[..., comp].transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, #adding a colorbar width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1 ), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') #end #end else: raise ValueError("{:d}D data not yet supported".format(numDims)) #end #-- Additional Formatting ------------------------------------ if not quiver: fig[comp].x_range.range_padding = 0 if numDims == 2: fig[comp].y_range.range_padding = 0 #end #end if legend: if numDims == 2: x_range = grid[0] * xscale y_range = grid[1] * yscale #The legends are not embedded into the plot but the text numbers on the top of plots. Refer to 1D line plot. legend_number = bm.Label( x=x_range[0] + (x_range[-1] - x_range[0]) * 0.005, y=y_range[-1] - (y_range[-1] - y_range[0]) * 0.115, text=label, render_mode='css', background_fill_color='white', background_fill_alpha=0.9, border_line_cap='round') fig[comp].add_layout(legend_number) #end #end if title: if comp < numCols: fig[comp].title.text = title #end #end if not legend: if numDims == 1: fig[comp].legend.visible = False #end #end gp = bl.gridplot(children=fig, toolbar_location='right', ncols=numCols, merge_tools=True) return gp
ld = 'dotted' else: ld = 'solid' if anm == 'FW' or anm == 'GIGA': fig_F.line(np.percentile(csizes[aidx, :, :], 50, axis=0), np.percentile(Fs[aidx, :, :], 50, axis=0) / np.percentile(Fs[2, :, :], 50, axis=0), line_color=pal[didx], line_width=8, line_dash=ld, legend=dnm if ld == 'solid' else None) rndlbl = bkm.Label(x=30, y=1.0, y_offset=-50, text='Uniform Subsampling', text_font_size='30pt') rndspan = bkm.Span(location=1.0, dimension='width', line_width=8, line_color='black', line_dash='40 40') fig_F.add_layout(rndspan) fig_F.add_layout(rndlbl) fig_F.legend.label_text_font_size = legend_font_size fig_F.legend.glyph_width = 40 fig_F.legend.glyph_height = 80 fig_F.legend.spacing = 20 fig_F.legend.orientation = 'horizontal'
def make_center_track(source): tools = "pan,wheel_zoom,box_zoom,box_select,hover,reset,crosshair" basic_tooltip = [("log_Rho_c", "$x{0.[000]}"), ("log_T_c", "$y{0.[000]}")] p = figure(plot_height=500, plot_width=500, tools=tools, title='Central properties', x_axis_label='log_center_Rho', y_axis_label='log_center_T', tooltips=basic_tooltip) p.title.align = 'center' p.outline_line_width = 3 p.outline_line_alpha = 0.3 p.line('log_center_Rho', 'log_center_T', color='blue', source=source, legend_label='primary') p.circle('log_center_Rho', 'log_center_T', color='blue', source=source, size=0, legend_label='primary') p.line('log_center_Rho_2', 'log_center_T_2', color='red', source=source, legend_label='secondary') p.circle('log_center_Rho_2', 'log_center_T_2', color='red', source=source, size=0, legend_label='secondary') p.line(HIgnition['rho'], HeIgnition['T'], line_dash='dotted', color='black') p.line(HeIgnition['rho'], HeIgnition['T'], line_dash='dotted', color='black') p.line(OIgnition['rho'], OIgnition['T'], line_dash='dotted', color='black') p.line(edegeneracy['rho'], edegeneracy['T'], line_dash='dotted', color='black') h_label = mpl.Label(x=HIgnition['rho'][0], y=HeIgnition['T'][0], text='H', render_mode='css', text_font_size='10pt') he_label = mpl.Label(x=HeIgnition['rho'][0], y=HeIgnition['T'][0], text='He', render_mode='css', text_font_size='10pt', x_offset=5, y_offset=-5) o_label = mpl.Label(x=OIgnition['rho'][0], y=OIgnition['T'][0], text='O', render_mode='css', text_font_size='10pt', x_offset=5, y_offset=-5) e_label = mpl.Label(x=edegeneracy['rho'][0], y=edegeneracy['T'][0], text='e-deg.', render_mode='css', text_font_size='10pt', x_offset=5, y_offset=-5) p.add_layout(h_label) p.add_layout(he_label) p.add_layout(o_label) p.add_layout(e_label) p.legend.location = "top_left" p.legend.click_policy = "hide" return p