Python bokeh.plotting() Examples
The following are 23
code examples of bokeh.plotting().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bokeh
, or try the search function
.
Example #1
Source File: interact_bls.py From lightkurve with MIT License | 6 votes |
def prepare_bls_datasource(result, loc): """Prepare a bls result for bokeh plotting Parameters ---------- result : BLS.model result The BLS model result to use loc : int Index of the "best" period. (Usually the max power) Returns ------- bls_source : Bokeh.plotting.ColumnDataSource Bokeh style source for plotting """ bls_source = ColumnDataSource(data=dict( period=result['period'], power=result['power'], depth=result['depth'], duration=result['duration'], transit_time=result['transit_time'])) bls_source.selected.indices = [loc] return bls_source
Example #2
Source File: interact_bls.py From lightkurve with MIT License | 6 votes |
def prepare_folded_datasource(folded_lc): """Prepare a FoldedLightCurve object for bokeh plotting. Parameters ---------- folded_lc : lightkurve.FoldedLightCurve The folded lightcurve Returns ------- folded_source : Bokeh.plotting.ColumnDataSource Bokeh style source for plotting """ folded_src = ColumnDataSource(data=dict( phase=np.sort(folded_lc.time), flux=folded_lc.flux[np.argsort(folded_lc.time)])) return folded_src # Helper functions for help text...
Example #3
Source File: plot.py From Pandas-Bokeh with MIT License | 6 votes |
def area(self, x=None, y=None, **kwds): """ Area plot Parameters ---------- x, y : label or position, optional Coordinates for each point. `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure """ return self(kind="area", x=x, y=y, **kwds)
Example #4
Source File: interact.py From lightkurve with MIT License | 6 votes |
def prepare_tpf_datasource(tpf, aperture_mask): """Prepare a bokeh DataSource object for selection glyphs Parameters ---------- tpf : TargetPixelFile TPF to be shown. aperture_mask : boolean numpy array The Aperture mask applied at the startup of interact Returns ------- tpf_source : bokeh.plotting.ColumnDataSource Bokeh object to be shown. """ npix = tpf.flux[0, :, :].size pixel_index_array = np.arange(0, npix, 1).reshape(tpf.flux[0].shape) xx = tpf.column + np.arange(tpf.shape[2]) yy = tpf.row + np.arange(tpf.shape[1]) xa, ya = np.meshgrid(xx, yy) tpf_source = ColumnDataSource(data=dict(xx=xa.astype(float), yy=ya.astype(float))) tpf_source.selected.indices = pixel_index_array[aperture_mask].reshape(-1).tolist() return tpf_source
Example #5
Source File: interact.py From lightkurve with MIT License | 6 votes |
def get_lightcurve_y_limits(lc_source): """Compute sensible defaults for the Y axis limits of the lightcurve plot. Parameters ---------- lc_source : bokeh.plotting.ColumnDataSource The lightcurve being shown. Returns ------- ymin, ymax : float, float Flux min and max limits. """ with warnings.catch_warnings(): # Ignore warnings due to NaNs warnings.simplefilter("ignore", AstropyUserWarning) flux = sigma_clip(lc_source.data['flux'], sigma=5, masked=False) low, high = np.nanpercentile(flux, (1, 99)) margin = 0.10 * (high - low) return low - margin, high + margin
Example #6
Source File: chart.py From chartify with Apache License 2.0 | 6 votes |
def _initialize_figure(self, x_axis_type, y_axis_type): x_range, y_range = None, None if x_axis_type == 'categorical': x_range = [] x_axis_type = 'auto' if y_axis_type == 'categorical': y_range = [] y_axis_type = 'auto' if x_axis_type == 'density': x_axis_type = 'linear' if y_axis_type == 'density': y_axis_type = 'linear' figure = bokeh.plotting.figure( x_range=x_range, y_range=y_range, y_axis_type=y_axis_type, x_axis_type=x_axis_type, plot_width=self.style.plot_width, plot_height=self.style.plot_height, tools='save', # toolbar_location='right', active_drag=None) return figure
Example #7
Source File: element.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def framewise(self): """ Property to determine whether the current frame should have framewise normalization enabled. Required for bokeh plotting classes to determine whether to send updated ranges for each frame. """ current_frames = [el for f in self.traverse(lambda x: x.current_frame) for el in (f.traverse(lambda x: x, [Element]) if f else [])] current_frames = util.unique_iterator(current_frames) return any(self.lookup_options(frame, 'norm').options.get('framewise') for frame in current_frames)
Example #8
Source File: plotting.py From gnomad_methods with MIT License | 5 votes |
def plot_hail_hist( hist_data: hl.Struct, title: str = "Plot", log: bool = False, fill_color: str = "#033649", outlier_fill_color: str = "#036564", line_color: str = "#033649", hover_mode: str = "mouse", hide_zeros: bool = False, ) -> bokeh.plotting.Figure: """ hist_data can (and should) come straight from ht.aggregate(hl.agg.hist(ht.data, start, end, bins)) :param hist_data: Data to plot :param title: Plot title :param log: Whether the y-axis should be log :param fill_color: Color to fill the histogram bars that fall within the hist boundaries :param outlier_fill_color: Color to fill the histogram bars that fall outside the hist boundaries :param line_color: Color of the lines around the histogram bars :param hover_mode: Hover mode; one of 'mouse' (default), 'vline' or 'hline' :param hide_zeros: Remove hist bars with 0 count :return: Histogram plot """ return plot_multi_hail_hist( {"hist": hist_data}, title=title, log=log, fill_color={"hist": fill_color}, outlier_fill_color={"hist": outlier_fill_color}, line_color=line_color, hover_mode=hover_mode, hide_zeros=hide_zeros, alpha=1.0, )
Example #9
Source File: geoplot.py From Pandas-Bokeh with MIT License | 5 votes |
def _get_figure(col): """Gets the bokeh.plotting.figure from a bokeh.layouts.column.""" from bokeh.layouts import column from bokeh.plotting import figure for children in col.children: if isinstance(children, type(figure())): return children elif isinstance(children, type(column())): return _get_figure(children)
Example #10
Source File: chart.py From chartify with Apache License 2.0 | 4 votes |
def set_legend_location(self, location, orientation='horizontal'): """Set the legend location. Args: location (str or tuple): Legend location. One of: - Outside of the chart: 'outside_top', 'outside_bottom', 'outside_right' - Within the chart area: 'top_left', 'top_center', 'top_right', 'center_left', 'center', 'center_right', 'bottom_left', 'bottom_center', 'bottom_right' - Coordinates: Tuple(Float, Float) - None: Removes the legend. orientation (str): 'horizontal' or 'vertical' Returns: Current chart object """ def add_outside_legend(legend_location, layout_location): self.figure.legend.location = legend_location if not self.figure.legend: warnings.warn( """ Legend location will not apply. Set the legend after plotting data. """, UserWarning) return self new_legend = self.figure.legend[0] new_legend.orientation = orientation self.figure.add_layout(new_legend, layout_location) if location == 'outside_top': add_outside_legend('top_left', 'above') # Re-render the subtitle so that it appears over the legend. subtitle_index = self.figure.renderers.index(self._subtitle_glyph) self.figure.renderers.pop(subtitle_index) self._subtitle_glyph = self._add_subtitle_to_figure( self._subtitle_glyph.text) elif location == 'outside_bottom': add_outside_legend('bottom_center', 'below') elif location == 'outside_right': add_outside_legend('top_left', 'right') elif location is None: self.figure.legend.visible = False else: self.figure.legend.location = location self.figure.legend.orientation = orientation vertical = self.axes._vertical # Reverse the legend order if self._reverse_vertical_legend: if orientation == 'vertical' and vertical: self.figure.legend[0].items = list( reversed(self.figure.legend[0].items)) return self
Example #11
Source File: element.py From holoviews with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _init_plot(self, key, element, plots, ranges=None): """ Initializes Bokeh figure to draw Element into and sets basic figure and axis attributes including axes types, labels, titles and plot height and width. """ subplots = list(self.subplots.values()) if self.subplots else [] axis_types, labels, plot_ranges = self._axes_props(plots, subplots, element, ranges) xlabel, ylabel, _ = labels x_axis_type, y_axis_type = axis_types properties = dict(plot_ranges) properties['x_axis_label'] = xlabel if 'x' in self.labelled or self.xlabel else ' ' properties['y_axis_label'] = ylabel if 'y' in self.labelled or self.ylabel else ' ' if not self.show_frame: properties['outline_line_alpha'] = 0 if self.show_title and self.adjoined is None: title = self._format_title(key, separator=' ') else: title = '' if self.toolbar != 'disable': tools = self._init_tools(element) properties['tools'] = tools properties['toolbar_location'] = self.toolbar else: properties['tools'] = [] properties['toolbar_location'] = None if self.renderer.webgl: properties['output_backend'] = 'webgl' properties.update(**self._plot_properties(key, element)) with warnings.catch_warnings(): # Bokeh raises warnings about duplicate tools but these # are not really an issue warnings.simplefilter('ignore', UserWarning) return bokeh.plotting.Figure(x_axis_type=x_axis_type, y_axis_type=y_axis_type, title=title, **properties)
Example #12
Source File: core.py From lightkurve with MIT License | 4 votes |
def _make_echelle_elements(self, deltanu, cmap='viridis', minimum_frequency=None, maximum_frequency=None, smooth_filter_width=.1, scale='linear', plot_width=490, plot_height=340, title='Echelle'): """Helper function to make the elements of the echelle diagram for bokeh plotting. """ if not hasattr(deltanu, 'unit'): deltanu = deltanu * self.periodogram.frequency.unit if smooth_filter_width: pgsmooth = self.periodogram.smooth(filter_width=smooth_filter_width) freq = pgsmooth.frequency # Makes code below more readable below else: freq = self.periodogram.frequency # Makes code below more readable ep, x_f, y_f = self._clean_echelle(deltanu=deltanu, minimum_frequency=minimum_frequency, maximum_frequency=maximum_frequency, smooth_filter_width=smooth_filter_width, scale=scale) fig = figure(plot_width=plot_width, plot_height=plot_height, x_range=(0, 1), y_range=(y_f[0].value, y_f[-1].value), title=title, tools='pan,box_zoom,reset', toolbar_location="above", border_fill_color="white") fig.yaxis.axis_label = r'Frequency [{}]'.format(freq.unit.to_string()) fig.xaxis.axis_label = r'Frequency / {:.3f} Mod. 1'.format(deltanu) lo, hi = np.nanpercentile(ep.value, [0.1, 99.9]) vlo, vhi = 0.3 * lo, 1.7 * hi vstep = (lo - hi)/500 color_mapper = LogColorMapper(palette="RdYlGn10", low=lo, high=hi) fig.image(image=[ep.value], x=0, y=y_f[0].value, dw=1, dh=y_f[-1].value, color_mapper=color_mapper, name='img') stretch_slider = RangeSlider(start=vlo, end=vhi, step=vstep, title='', value=(lo, hi), orientation='vertical', width=10, height=230, direction='rtl', show_value=False, sizing_mode='fixed', name='stretch') def stretch_change_callback(attr, old, new): """TPF stretch slider callback.""" fig.select('img')[0].glyph.color_mapper.high = new[1] fig.select('img')[0].glyph.color_mapper.low = new[0] stretch_slider.on_change('value', stretch_change_callback) return fig, stretch_slider
Example #13
Source File: plot_utils.py From arviz with Apache License 2.0 | 4 votes |
def get_plotting_function(plot_name, plot_module, backend): """Return plotting function for correct backend.""" _backend = { "mpl": "matplotlib", "bokeh": "bokeh", "matplotlib": "matplotlib", } if backend is None: backend = rcParams["plot.backend"] backend = backend.lower() try: backend = _backend[backend] except KeyError: raise KeyError( "Backend {} is not implemented. Try backend in {}".format( backend, set(_backend.values()) ) ) if backend == "bokeh": try: import bokeh assert packaging.version.parse(bokeh.__version__) >= packaging.version.parse("1.4.0") except (ImportError, AssertionError): raise ImportError( "'bokeh' backend needs Bokeh (1.4.0+) installed." " Please upgrade or install" ) # Perform import of plotting method # TODO: Convert module import to top level for all plots module = importlib.import_module( "arviz.plots.backends.{backend}.{plot_module}".format( backend=backend, plot_module=plot_module ) ) plotting_method = getattr(module, plot_name) return plotting_method
Example #14
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def mapplot(df, x, y, **kwargs): # Get data of x and y columns: if not x in df.columns: raise ValueError( "<x> parameter has to be a column name of the provided dataframe." ) if not y in df.columns: raise ValueError( "<y> parameter has to be a column name of the provided dataframe." ) latitude = df[y] longitude = df[x] # Check if NaN values are in x & y columns: if (pd.isnull(latitude).sum() > 0) or (pd.isnull(longitude).sum() > 0): raise ValueError( "There are NaN values in the <x> or <y> column. The map plot API of Pandas Bokeh does not support this. Please drop the NaN rows for plotting." ) # Check values of longitude and latitude: if not (check_type(latitude) == "numeric" and check_type(longitude) == "numeric"): raise ValueError( "<x> and <y> have to be numeric columns of the DataFrame. Further they correspond to longitude, latitude in WGS84 projection." ) if not (np.min(latitude) > -90 and np.max(latitude) < 90): raise ValueError( "All values of the y-column have to be restricted to (-90, 90). The <y> value corresponds to the latitude in WGS84 projection." ) if not (np.min(longitude) > -180 and np.max(longitude) < 180): raise ValueError( "All values of the x-column have to be restricted to (-180, 180). The <x> value corresponds to the longitude in WGS84 projection." ) # Convert longitude & latitude coordinates to Web Mercator projection: if "x" in df.columns or "y" in df.columns: raise ValueError( "The map plot API overrides the columns named 'x' and 'y' with the coordinates for plotting. Please rename your columns 'x' and 'y'." ) RADIUS = 6378137.0 df["y"] = np.log(np.tan(np.pi / 4 + np.radians(latitude) / 2)) * RADIUS df["x"] = np.radians(longitude) * RADIUS return geoplot(df, **kwargs) ############################################################################## ###########Class to add Bokeh plotting methods to Pandas DataFrame ##############################################################################
Example #15
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def line(self, x=None, y=None, **kwargs): """ Plot DataFrame columns as lines. This function is useful to plot lines using DataFrame's values as coordinates. Parameters ---------- x : int or str, optional Columns to use for the horizontal axis. Either the location or the label of the columns to be used. By default, it will use the DataFrame indices. y : int, str, or list of them, optional The values to be plotted. Either the location or the label of the columns to be used. By default, it will use the remaining DataFrame numeric columns. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure or Bokeh.layouts.row Examples -------- .. plot:: :context: close-figs The following example shows the populations for some animals over the years. >>> df = pd.DataFrame({ ... 'pig': [20, 18, 489, 675, 1776], ... 'horse': [4, 25, 281, 600, 1900] ... }, index=[1990, 1997, 2003, 2009, 2014]) >>> lines = df.plot_bokeh.line() .. plot:: :context: close-figs The following example shows the relationship between both populations. >>> lines = df.plot_bokeh.line(x='pig', y='horse') """ return self(kind="line", x=x, y=y, **kwargs)
Example #16
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def step(self, x=None, y=None, **kwargs): """ Plot DataFrame columns as step lines. This function is useful to plot step lines using DataFrame's values as coordinates. Parameters ---------- x : int or str, optional Columns to use for the horizontal axis. Either the location or the label of the columns to be used. By default, it will use the DataFrame indices. y : int, str, or list of them, optional The values to be plotted. Either the location or the label of the columns to be used. By default, it will use the remaining DataFrame numeric columns. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure or Bokeh.layouts.row Examples -------- .. plot:: :context: close-figs The following example shows the populations for some animals over the years. >>> df = pd.DataFrame({ ... 'pig': [20, 18, 489, 675, 1776], ... 'horse': [4, 25, 281, 600, 1900] ... }, index=[1990, 1997, 2003, 2009, 2014]) >>> steps = df.plot_bokeh.step() .. plot:: :context: close-figs The following example shows the relationship between both populations. >>> steps = df.plot_bokeh.step(x='pig', y='horse') """ return self(kind="step", x=x, y=y, **kwargs)
Example #17
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def point(self, x=None, y=None, **kwargs): """ Plot DataFrame columns as points. This function is useful to plot lines using DataFrame's values as coordinates. Parameters ---------- x : int or str, optional Columns to use for the horizontal axis. Either the location or the label of the columns to be used. By default, it will use the DataFrame indices. y : int, str, or list of them, optional The values to be plotted. Either the location or the label of the columns to be used. By default, it will use the remaining DataFrame numeric columns. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure or Bokeh.layouts.row Examples -------- .. plot:: :context: close-figs The following example shows the populations for some animals over the years. >>> df = pd.DataFrame({ ... 'pig': [20, 18, 489, 675, 1776], ... 'horse': [4, 25, 281, 600, 1900] ... }, index=[1990, 1997, 2003, 2009, 2014]) >>> lines = df.plot_bokeh.point() .. plot:: :context: close-figs The following example shows the relationship between both populations. >>> lines = df.plot_bokeh.point(x='pig', y='horse') """ return self(kind="point", x=x, y=y, **kwargs)
Example #18
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def hist(self, **kwds): """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one figure. This is useful when the DataFrame's Series are in a similar scale. Parameters ---------- ... bins : int, default 10 Number of histogram bins to be used. **kwds Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure See Also -------- DataFrame.hist : Draw histograms per DataFrame's Series. Series.hist : Draw a histogram with Series' data. Examples -------- When we draw a dice 6000 times, we expect to get each value around 1000 times. But when we draw two dices and sum the result, the distribution is going to be quite different. A histogram illustrates those distributions. .. plot:: :context: close-figs >>> df = pd.DataFrame( ... np.random.randint(1, 7, 6000), ... columns = ['one']) >>> df['two'] = df['one'] + np.random.randint(1, 7, 6000) >>> ax = df.plot_bokeh.hist(bins=12, alpha=0.5) """ return self(kind="hist", **kwds)
Example #19
Source File: interact_bls.py From lightkurve with MIT License | 4 votes |
def make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source, help_source): """Make a scatter plot of a FoldedLightCurve. Parameters ---------- f : lightkurve.LightCurve Folded light curve to plot f_model_lc : lightkurve.LightCurve Model folded light curve to plot f_source : bokeh.plotting.ColumnDataSource Bokeh style source object for plotting folded light curve f_model_lc_source : bokeh.plotting.ColumnDataSource Bokeh style source object for plotting model folded light curve help_source : bokeh.plotting.ColumnDataSource Bokeh style source object for rendering help button Returns ------- fig : bokeh.plotting.figure Bokeh figure object """ # Build Figure fig = figure(title='Folded Light Curve', plot_height=340, plot_width=450, tools="pan,box_zoom,reset", toolbar_location="below", border_fill_color="#FFFFFF", active_drag="box_zoom") fig.title.offset = -10 fig.yaxis.axis_label = 'Flux' fig.xaxis.axis_label = 'Phase' # Scatter point for data fig.circle('phase', 'flux', line_width=1, color='#191919', source=f_source, nonselection_line_color='#191919', nonselection_line_alpha=1.0, size=0.1) # Line plot for model fig.step('phase', 'flux', line_width=3, color='firebrick', source=f_model_lc_source, nonselection_line_color='firebrick', nonselection_line_alpha=1.0) # Help button question_mark = Text(x="phase", y="flux", text="helpme", text_color="grey", text_align='center', text_baseline="middle", text_font_size='12px', text_font_style='bold', text_alpha=0.6) fig.add_glyph(help_source, question_mark) help = fig.circle('phase', 'flux', alpha=0.0, size=15, source=help_source, line_width=2, line_color='grey', line_alpha=0.6) tooltips = help_source.data['help'][0] fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help], mode='mouse', point_policy="snap_to_data")) return fig
Example #20
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def pie(self, y=None, **kwds): """ Generate a pie plot. A pie plot is a proportional representation of the numerical data in a column. This function wraps :meth:`matplotlib.pyplot.pie` for the specified column. If no column reference is passed and ``subplots=True`` a pie plot is drawn for each numerical column independently. Parameters ---------- y : int or label, optional Label or position of the column(s) to plot. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot_bokeh`. Returns ------- Bokeh.plotting.figure See Also -------- Series.plot.pie : Generate a pie plot for a Series. DataFrame.plot : Make plots of a DataFrame. Examples -------- In the example below we have a DataFrame with the information about planet's mass and radius. We pass the the 'mass' column to the pie function to get a pie plot. .. plot:: :context: close-figs >>> df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], ... 'radius': [2439.7, 6051.8, 6378.1]}, ... index=['Mercury', 'Venus', 'Earth']) >>> plot = df.plot_bokeh.pie(y='mass') When you pass multiple y-columns, the plot contains several nested pieplots: .. plot:: :context: close-figs >>> plot = df.plot.pie() """ return self(kind="pie", y=y, **kwds)
Example #21
Source File: plot.py From Pandas-Bokeh with MIT License | 4 votes |
def _initialize_rangetool(p, x_axis_type, source): """ Initializes the range tool chart and slider. Parameters ---------- p : Bokeh.plotting.figure Bokeh plot that the figure tool is going to supplement. x_axis_type : str Type of the xaxis (ex. datetime) source : Bokeh.models.sources Data Returns ------- Bokeh.plotting.figure """ max_y_range = 0 # Initialize range tool plot p_rangetool = figure( title="Drag the box to change the range above.", plot_height=130, plot_width=p.plot_width, y_range=p.y_range, x_axis_type=x_axis_type, y_axis_type=None, tools="", toolbar_location=None, ) # Need to explicitly set the initial range of the plot for the range tool. start_index = int(0.75 * len(source["__x__values"])) p.x_range = Range1d(source["__x__values"][start_index], source["__x__values"][-1]) range_tool = RangeTool(x_range=p.x_range) range_tool.overlay.fill_color = "navy" range_tool.overlay.fill_alpha = 0.2 p_rangetool.ygrid.grid_line_color = None p_rangetool.add_tools(range_tool) p_rangetool.toolbar.active_multi = range_tool return p_rangetool
Example #22
Source File: interact_bls.py From lightkurve with MIT License | 4 votes |
def make_lightcurve_figure_elements(lc, model_lc, lc_source, model_lc_source, help_source): """Make a figure with a simple light curve scatter and model light curve line. Parameters ---------- lc : lightkurve.LightCurve Light curve to plot model_lc : lightkurve.LightCurve Model light curve to plot lc_source : bokeh.plotting.ColumnDataSource Bokeh style source object for plotting light curve model_lc_source : bokeh.plotting.ColumnDataSource Bokeh style source object for plotting model light curve help_source : bokeh.plotting.ColumnDataSource Bokeh style source object for rendering help button Returns ------- fig : bokeh.plotting.figure Bokeh figure object """ # Make figure fig = figure(title='Light Curve', plot_height=300, plot_width=900, tools="pan,box_zoom,reset", toolbar_location="below", border_fill_color="#FFFFFF", active_drag="box_zoom") fig.title.offset = -10 fig.yaxis.axis_label = 'Flux (e/s)' if lc.time.format == 'bkjd': fig.xaxis.axis_label = 'Time - 2454833 (days)' elif lc.time.format == 'btjd': fig.xaxis.axis_label = 'Time - 2457000 (days)' else: fig.xaxis.axis_label = 'Time (days)' ylims = [np.nanmin(lc.flux.value), np.nanmax(lc.flux.value)] fig.y_range = Range1d(start=ylims[0], end=ylims[1]) # Add light curve fig.circle('time', 'flux', line_width=1, color='#191919', source=lc_source, nonselection_line_color='#191919', size=0.5, nonselection_line_alpha=1.0) # Add model fig.step('time', 'flux', line_width=1, color='firebrick', source=model_lc_source, nonselection_line_color='firebrick', nonselection_line_alpha=1.0) # Help button question_mark = Text(x="time", y="flux", text="helpme", text_color="grey", text_align='center', text_baseline="middle", text_font_size='12px', text_font_style='bold', text_alpha=0.6) fig.add_glyph(help_source, question_mark) help = fig.circle('time', 'flux', alpha=0.0, size=15, source=help_source, line_width=2, line_color='grey', line_alpha=0.6) tooltips = help_source.data['help'][0] fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help], mode='mouse', point_policy="snap_to_data")) return fig
Example #23
Source File: plotting.py From gnomad_methods with MIT License | 4 votes |
def plot_hail_hist_cumulative( hist_data: hl.Struct, title: str = "Plot", normalize: bool = True, line_color: str = "#036564", line_width: int = 3, log: bool = False, hover_mode: str = "mouse", ) -> bokeh.plotting.Figure: """ hist_data can (and should) come straight from ht.aggregate(hl.agg.hist(ht.data, start, end, bins)) :param hist_data: Data to plot :param title: Plot title :param normalize: Whether to normalize the data (0,1) :param line_color: Color of the line :param line_width: Width of the line :param log: Whether the y-axis should be log :param hover_mode: Hover mode; one of 'mouse' (default), 'vline' or 'hline' :return: Histogram plot """ cumulative_data = np.cumsum(hist_data.bin_freq) + hist_data.n_smaller np.append(cumulative_data, [cumulative_data[-1] + hist_data.n_larger]) num_data_points = max(cumulative_data) if normalize: cumulative_data = cumulative_data / num_data_points p = ( figure(title=title, y_axis_type="log", tools=TOOLS) if log else figure(title=title, tools=TOOLS) ) p.add_layout(Title(text=f"({num_data_points:,} data points)"), "above") p.select_one(HoverTool).tooltips = [("index", "$index"), ("(x,y)", "(@x, @y)")] p.select_one(HoverTool).mode = hover_mode data_source = ColumnDataSource( {"x": hist_data.bin_edges[:-1], "y": cumulative_data} ) p.line( x="x", y="y", line_color=line_color, line_width=line_width, source=data_source ) return p