Here are the examples of the python api bokeh.models.ranges.Range1d taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
18 Examples
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_screenshot_as_png():
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=20, plot_width=20, toolbar_location=None,
outline_line_color=None, background_fill_color=None,
border_fill_color=None)
png = bie.get_screenshot_as_png(layout)
assert png.size == (20, 20)
# a 20x20px image of transparent pixels
assert png.tobytes() == ("\x00"*1600).encode()
@pytest.mark.unit
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_screenshot_as_png_with_driver(webdriver):
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=20, plot_width=20, toolbar_location=None,
outline_line_color=None, background_fill_color=None,
border_fill_color=None)
png = bie.get_screenshot_as_png(layout, driver=webdriver)
assert png.size == (20, 20)
# a 20x20px image of transparent pixels
assert png.tobytes() == ("\x00"*1600).encode()
@pytest.mark.unit
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_screenshot_as_png_large_plot(webdriver):
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=800, plot_width=800, toolbar_location=None,
outline_line_color=None, background_fill_color=None,
border_fill_color=None)
bie.get_screenshot_as_png(layout, driver=webdriver)
# LC: Although the window size doesn't match the plot dimensions (unclear
# why), the window resize allows for the whole plot to be captured
assert webdriver.get_window_size() == {'width': 1366, 'height': 768}
@pytest.mark.unit
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_svgs_no_svg_present():
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=20, plot_width=20, toolbar_location=None)
svgs = bie.get_svgs(layout)
assert svgs == []
@pytest.mark.unit
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_layout_html_resets_plot_dims():
initial_height, initial_width = 200, 250
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=initial_height, plot_width=initial_width)
bie.get_layout_html(layout, height=100, width=100)
assert layout.plot_height == initial_height
assert layout.plot_width == initial_width
def test_layout_html_on_child_first():
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_layout_html_on_child_first():
p = Plot(x_range=Range1d(), y_range=Range1d())
bie.get_layout_html(p, height=100, width=100)
layout = row(p)
bie.get_layout_html(layout)
def test_layout_html_on_parent_first():
3
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_layout_html_on_parent_first():
p = Plot(x_range=Range1d(), y_range=Range1d())
layout = row(p)
bie.get_layout_html(layout)
bie.get_layout_html(p, height=100, width=100)
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
@patch('PIL.Image.Image')
3
Source : test_plots.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_plot_add_layout_raises_error_if_not_render():
plot = figure()
with pytest.raises(ValueError):
plot.add_layout(Range1d())
def test_plot_add_layout_adds_label_to_plot_renderers():
3
Source : test_plots.py
with MIT License
from rthorst
with MIT License
from rthorst
def test__check_compatible_scale_and_ranges_compat_numeric():
plot = Plot(x_scale=LinearScale(), x_range=Range1d())
check = plot._check_compatible_scale_and_ranges()
assert check == []
plot = Plot(y_scale=LogScale(), y_range=DataRange1d())
check = plot._check_compatible_scale_and_ranges()
assert check == []
def test__check_compatible_scale_and_ranges_compat_factor():
3
Source : test_helpers.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_axis_type_auto(self):
assert(bph._get_axis_class("auto", FactorRange(), 0)) == (CategoricalAxis, {})
assert(bph._get_axis_class("auto", FactorRange(), 1)) == (CategoricalAxis, {})
assert(bph._get_axis_class("auto", DataRange1d(), 0)) == (LinearAxis, {})
assert(bph._get_axis_class("auto", DataRange1d(), 1)) == (LinearAxis, {})
assert(bph._get_axis_class("auto", Range1d(), 0)) == (LinearAxis, {})
assert(bph._get_axis_class("auto", Range1d(), 1)) == (LinearAxis, {})
assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 0)) == (DatetimeAxis, {})
assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 1)) == (DatetimeAxis, {})
@pytest.mark.parametrize('range', _RANGES)
3
Source : test_helpers.py
with MIT License
from rthorst
with MIT License
from rthorst
def test__get_scale_numeric_range_linear_axis():
s = bph._get_scale(Range1d(), "linear")
assert isinstance(s, LinearScale)
s = bph._get_scale(Range1d(), "datetime")
assert isinstance(s, LinearScale)
s = bph._get_scale(Range1d(), "auto")
assert isinstance(s, LinearScale)
def test__get_scale_numeric_range_log_axis():
0
Source : ui_main.py
with Apache License 2.0
from IntelLabs
with Apache License 2.0
from IntelLabs
def create_custom_trends_graph():
header = gd["reports"][4]
phrases = gd.values[:, 9]
imp_change = gd.values[:, 10]
phrases_h, changes_h = [], []
phrases_c, changes_c = [], []
text_h, text_c = [], []
custom_count = 0
for i in range(len(phrases)):
phrase = phrases[i]
change = float(imp_change[i])
if phrase in custom_nps:
if custom_count > 30:
logger.warning("too many custom phrases (>30). Showing partial list")
break
phrase = cut_phrase(phrase)
if change > 0:
phrases_h.append(phrase)
changes_h.append(change)
text_h.append("+" + str(("%.1f" % change)) + "%")
else:
phrases_c.append(phrase)
changes_c.append(change)
text_c.append(str(("%.1f" % change)) + "%")
custom_count += 1
changes = changes_h + changes_c
text = text_h + text_c
trends = phrases_h + phrases_c
colors = []
if len(changes_h) > 0:
for i in range(len(changes_h)):
colors.append("#1d6d34")
if len(changes_c) > 0:
for i in range(len(changes_c)):
colors.append("#912605")
if len(changes) < 10: # pad with 10 blanks
changes += [0] * (10 - len(changes))
text += " " * (10 - len(text))
trends += [str((10 - len(trends)) - i) for i in range(0, (10 - len(trends)))]
colors += ["white"] * (10 - len(colors))
source = ColumnDataSource(
dict(y=trends[::-1], x=changes[::-1], colors=colors[::-1], text=text[::-1])
)
plot = figure(
title=header,
plot_width=600,
plot_height=400,
tools="save",
x_range=ranges.Range1d(start=min(changes) - 10, end=max(changes) + 20),
y_range=source.data["y"],
tooltips="@y < br>change: @x",
)
labels = LabelSet(
x=max(changes) + 5,
y="y",
text="text",
level="glyph",
x_offset=0,
y_offset=-10,
source=source,
render_mode="canvas",
)
plot.hbar(source=source, right="x", y="y", left=0, height=0.5, color="colors")
plot.add_layout(labels)
return plot
def create_trend_graphs(top_n):
0
Source : ui_main.py
with Apache License 2.0
from IntelLabs
with Apache License 2.0
from IntelLabs
def create_trend_graphs(top_n):
header_h = gd["reports"][2]
header_c = gd["reports"][3]
phrases = gd.values[:, 9] # all trends
imp_change = gd.values[:, 10]
data_h, data_c = {}, {}
text_h, text_c = [], []
hot, cold = 0, 0 # counters for each list
plot_h = figure(plot_width=600, plot_height=400, title=header_h)
plot_c = figure(plot_width=600, plot_height=400, title=header_c)
for i in range(len(phrases)):
if hot == top_n and cold == top_n:
break
phrase = phrases[i]
change = float(imp_change[i])
if phrase in white_list:
phrase = cut_phrase(phrase)
if change > 0:
if hot < top_n:
data_h[phrase] = change
text_h.append("+" + str(("%.1f" % change)) + "%")
hot += 1
elif cold < top_n:
data_c[phrase] = change
text_c.append(str(("%.1f" % change)) + "%")
cold += 1
if len(data_h.keys()) > 0:
phrases_h = sorted(data_h, key=data_h.get)
changes_h = sorted(data_h.values())
source = ColumnDataSource(dict(y=phrases_h, x=changes_h, text=text_h[::-1]))
title = header_h
plot_h = figure(
plot_width=600,
plot_height=400,
tools="save",
title=title,
x_range=ranges.Range1d(start=0, end=max(changes_h) + 20),
y_range=source.data["y"],
tooltips="@y < br>change: @x",
)
labels = LabelSet(
x="x",
y="y",
text="text",
level="glyph",
x_offset=5,
y_offset=0,
source=source,
render_mode="canvas",
text_color="#1d6d34",
)
plot_h.hbar(source=source, right="x", y="y", left=0, height=0.5, color="#1d6d34")
plot_h.add_layout(labels)
plot_h.xaxis.visible = False
if len(data_c.keys()) > 0:
phrases_c = sorted(data_c, key=data_c.get)
changes_c = sorted(data_c.values())
source = ColumnDataSource(dict(y=phrases_c[::-1], x=changes_c[::-1], text=text_c[::-1]))
plot_c = figure(
plot_width=600,
plot_height=400,
tools="save",
title=header_c,
x_range=ranges.Range1d(start=min(changes_c) - 10, end=20),
y_range=source.data["y"],
tooltips="@y < br>change: @x",
)
labels = LabelSet(
x=0,
y="y",
text="text",
level="glyph",
x_offset=5,
y_offset=0,
source=source,
render_mode="canvas",
text_color="#912605",
)
plot_c.hbar(source=source, right="x", y="y", left=0, height=0.5, color="#912605")
plot_c.add_layout(labels)
plot_c.xaxis.visible = False
return [plot_h, plot_c]
def create_trend_clustering_graph(top_n):
0
Source : plot.py
with MIT License
from PatrikHlobil
with MIT License
from PatrikHlobil
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
"""
# 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
0
Source : test_export.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_get_svgs_with_svg_present(webdriver):
def fix_ids(svg):
svg = re.sub(r'id="\w{12}"', 'id="X"', svg)
svg = re.sub(r'url\(#\w{12}\)', 'url(#X)', svg)
return svg
layout = Plot(x_range=Range1d(), y_range=Range1d(),
plot_height=20, plot_width=20, toolbar_location=None,
outline_line_color=None, border_fill_color=None,
background_fill_color="red", output_backend="svg")
svg0 = fix_ids(bie.get_svgs(layout, driver=webdriver)[0])
svg1 = fix_ids(bie.get_svgs(layout, driver=webdriver)[0])
svg2 = (
' < svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
'width="20" height="20" style="width: 20px; height: 20px;">'
' < defs/>'
' < g>'
' < g transform="scale(1,1) translate(0.5,0.5)">'
' < rect fill="#FFFFFF" stroke="none" x="0" y="0" width="20" height="20"/>'
' < rect fill="red" stroke="none" x="5" y="5" width="10" height="10"/>'
' < g/>'
' < /g>'
' < /g>'
' < /svg>'
)
assert svg0 == svg2
assert svg1 == svg2
def test_get_layout_html_resets_plot_dims():
0
Source : test_plots.py
with MIT License
from rthorst
with MIT License
from rthorst
def test_bad_extra_range_name(self):
p = figure()
p.xaxis.x_range_name="junk"
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith(
"E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [LinearAxis"
)
p = figure()
p.extra_x_ranges['foo'] = Range1d()
p.grid.x_range_name="junk"
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith(
"E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [Grid"
)
assert mock_logger.error.call_args[0][0].count("Grid") == 2
# test whether adding a figure (*and* it's extra ranges)
# to another's references doesn't create a false positive
p, dep = figure(), figure()
dep.extra_x_ranges['foo'] = Range1d()
dep.grid.x_range_name="foo"
p.x_range.callback = CustomJS(code = "", args = {"dep": dep})
assert dep in p.references()
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 0
def test_plot_add_layout_raises_error_if_not_render():
0
Source : test_plots.py
with MIT License
from rthorst
with MIT License
from rthorst
def get_range_instance():
return Range1d(0, 42)
def test_plot_with_no_title_specified_creates_an_empty_title():
0
Source : bokeh_figures.py
with MIT License
from SolarArbiter
with MIT License
from SolarArbiter
def scatter(timeseries_value_cds, timeseries_meta_cds, units):
"""
Scatter plot of one or more forecasts and observations.
Parameters
----------
timeseries_value_cds: bokeh.models.ColumnDataSource
ColumnDataSource of timeseries data. See
:py:func:`solarforecastarbiter.reports.reoports.figures.construct_timeseries_cds`
for format.
timeseries_meta_cds: bokeh.models.ColumnDataSource
ColumnDataSource of metadata for each Observation Forecast pair. See
:py:func:`solarforecastarbiter.reports.reoports.figures.construct_timeseries_cds`
for format.
Returns
-------
fig : bokeh.plotting.figure
""" # NOQA
xy_min, xy_max = _get_scatter_limits(timeseries_value_cds)
# match_aspect=True does not work well, so these need to be close
plot_height = 400
# width will be updated later based on label length
plot_width = plot_height + 50
fig = figure(
plot_width=plot_width, plot_height=plot_height, match_aspect=True,
x_range=Range1d(xy_min, xy_max), y_range=Range1d(xy_min, xy_max),
tools='pan,wheel_zoom,box_zoom,box_select,lasso_select,reset,save',
name='scatter')
kwargs = dict(size=6, line_color=None)
palette = cycle(PALETTE)
# accumulate labels and plot objects for manual legend
scatters_labels = []
for fxhash in np.unique(timeseries_meta_cds.data['forecast_hash']):
metadata = _extract_metadata_from_cds(
timeseries_meta_cds, fxhash, 'forecast_hash')
pair_indices = _boolean_filter_indices_by_pair(
timeseries_value_cds, metadata['pair_index'])
view = CDSView(source=timeseries_value_cds,
filters=[BooleanFilter(pair_indices)])
label = metadata['forecast_name']
r = fig.scatter(
x='observation_values', y='forecast_values',
source=timeseries_value_cds, view=view,
fill_color=next(palette), **kwargs)
scatters_labels.append((label, [r]))
# manual legend so it can be placed outside the plot area
legend = Legend(items=scatters_labels, location='top_center',
click_policy='hide')
fig.add_layout(legend, 'right')
# compute new plot width accounting for legend label text width.
# also considered using second figure for legend so it doesn't
# distort the first when text length/size changes. unfortunately,
# that doesn't work due to bokeh's inability to communicate legend
# information across figures.
# widest part of the legend
max_legend_length = max((len(label) for label, _ in scatters_labels))
px_per_length = 7.75 # found through trial and error
fig.plot_width = int(fig.plot_width + max_legend_length * px_per_length)
label = f'({units})'
fig.xaxis.axis_label = 'Observed ' + label
fig.yaxis.axis_label = 'Forecast ' + label
return fig
def construct_metrics_cds(metrics, rename=None):