本文整理汇总了Python中bokeh.plotting方法的典型用法代码示例。如果您正苦于以下问题:Python bokeh.plotting方法的具体用法?Python bokeh.plotting怎么用?Python bokeh.plotting使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bokeh
的用法示例。
在下文中一共展示了bokeh.plotting方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prepare_bls_datasource
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例2: prepare_folded_datasource
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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...
示例3: prepare_tpf_datasource
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例4: get_lightcurve_y_limits
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例5: _initialize_figure
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例6: area
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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)
示例7: framewise
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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)
示例8: _get_figure
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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)
示例9: plot_hail_hist
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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,
)
示例10: _make_echelle_elements
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例11: make_lightcurve_figure_elements
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例12: make_folded_figure_elements
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例13: get_plotting_function
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例14: set_legend_location
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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
示例15: _init_plot
# 需要导入模块: import bokeh [as 别名]
# 或者: from bokeh import plotting [as 别名]
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)