Here are the examples of the python api bokeh.models.Plot taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
34 Examples
3
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
def render_network_bokeh(CRN,layout="force", layoutfunc = None, plot_reactions = True, plot_species = True, plot_edges = True, plot_arrows = True,
iterations=2000,rseed=30,posscale=1,export=False,species_glyph_size = 12, reaction_glyph_size = 8, export_name = None, **keywords):
DG, DGspec, DGrxn = generate_networkx_graph(CRN,**keywords) #this creates the networkx objects
plot = Plot(plot_width=500, plot_height=500, x_range=Range1d(-500, 500), y_range=Range1d(-500, 500)) #this generates a
show_im = False
images = None
if("imagedict" in keywords and keywords["imagedict"] is not None):
show_im = True
if(export):
plot.output_backend = "svg"
graphPlot(DG,DGspec,DGrxn,plot,layout=layout,posscale=posscale,iterations=iterations,rseed=rseed,show_species_images=show_im,
layoutfunc=layoutfunc, plot_reactions = plot_reactions, plot_species = plot_species, plot_edges = plot_edges, plot_arrows = plot_arrows,
species_glyph_size = species_glyph_size, reaction_glyph_size = reaction_glyph_size)
if(export):
if export_name is None:
raise ValueError("To export you must supply export_name keyword.")
export_svgs(plot,filename=export_name+".svg")
return plot
3
View Source File : vtk.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : holoviz
License : BSD 3-Clause "New" or "Revised" License
Project Creator : holoviz
def _construct_colorbars(self, color_mappers=None):
if not color_mappers:
color_mappers = self.color_mappers
from bokeh.models import Plot, ColorBar, FixedTicker
cbs = []
for color_mapper in color_mappers:
ticks = np.linspace(color_mapper.low, color_mapper.high, 5)
cbs.append(ColorBar(
color_mapper=color_mapper,
title=color_mapper.name,
ticker=FixedTicker(ticks=ticks),
label_standoff=5, background_fill_alpha=0, orientation='horizontal', location=(0, 0)
))
plot = Plot(toolbar_location=None, frame_height=0, sizing_mode='stretch_width',
outline_line_width=0)
[plot.add_layout(cb, 'below') for cb in cbs]
return plot
def construct_colorbars(self, infer=True):
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def verify_axis(self, axis_name):
plot = Plot()
range_obj = getattr(plot, 'extra_{}_ranges'.format(axis_name))
range_obj['foo_range'] = self.get_range_instance()
assert range_obj['foo_range']
def test_x_range(self):
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_plot_with_no_title_specified_creates_an_empty_title():
plot = Plot()
assert plot.title.text == ""
def test_plot__scale_classmethod():
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test__check_required_scale_has_scales():
plot = Plot()
check = plot._check_required_scale()
assert check == []
def test__check_required_scale_missing_scales():
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test__check_required_scale_missing_scales():
plot = Plot(x_scale=None, y_scale=None)
check = plot._check_required_scale()
assert check != []
def test__check_compatible_scale_and_ranges_compat_numeric():
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : 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
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test__check_compatible_scale_and_ranges_compat_factor():
plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange())
check = plot._check_compatible_scale_and_ranges()
assert check == []
def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range():
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range():
plot = Plot(x_scale=LinearScale(), x_range=FactorRange())
check = plot._check_compatible_scale_and_ranges()
assert check != []
def test__check_compatible_scale_and_ranges_incompat_factor_scale_and_numeric_range():
3
View Source File : test_plots.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test__check_compatible_scale_and_ranges_incompat_factor_scale_and_numeric_range():
plot = Plot(x_scale=CategoricalScale(), x_range=DataRange1d())
check = plot._check_compatible_scale_and_ranges()
assert check != []
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
3
View Source File : test_client_server.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_session_show_adds_obj_to_curdoc_if_necessary(m):
session = ClientSession()
session._document = Document()
p = Plot()
assert session.document.roots == []
session.show(p)
assert session.document.roots == [p]
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_event_constructor_plot():
model = Plot()
event = events.Event(model)
assert event._model_id == model.id
def test_buttonclick_constructor_button():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_lodstart_constructor_plot():
model = Plot()
event = events.LODStart(model)
assert event._model_id == model.id
def test_lodend_constructor_button():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_lodend_constructor_plot():
model = Plot()
event = events.LODEnd(model)
assert event._model_id == model.id
def test_plotevent_constructor_button():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_plotevent_constructor_plot():
model = Plot()
event = events.PlotEvent(model)
assert event._model_id == model.id
def test_pointEvent_constructor_plot():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_pointEvent_constructor_plot():
model = Plot()
event = events.PointEvent(model, sx=3, sy=-2, x=10, y=100)
assert event.sx == 3
assert event.sy == -2
assert event.x == 10
assert event.y == 100
assert event._model_id == model.id
def test_pointevent_constructor_button():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_pointevent_subclass_constructor_plot():
model = Plot()
for subcls in point_events:
event = subcls(model, sx=3, sy=-2, x=10, y=100)
assert event.sx == 3
assert event.sy == -2
assert event.x == 10
assert event.y == 100
assert event._model_id == model.id
def test_pointevent_subclass_constructor_button():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_atomic_plot_event_callbacks():
plot = Plot()
for event_cls in [events.LODStart, events.LODEnd]:
test_callback = EventCallback()
plot.on_event(event_cls, test_callback)
assert test_callback.event_name == None
plot._trigger_event(event_cls(plot))
assert test_callback.event_name == event_cls.event_name
def test_pointevent_callbacks():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_pointevent_callbacks():
plot = Plot()
payload = dict(sx=3, sy=-2, x=10, y=100)
for event_cls in point_events:
test_callback = EventCallback(['sx','sy','x','y'])
plot.on_event(event_cls, test_callback)
assert test_callback.event_name == None
plot._trigger_event(event_cls(plot, **payload))
assert test_callback.event_name == event_cls.event_name
assert test_callback.payload == payload
def test_mousewheel_callbacks():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_mousewheel_callbacks():
plot = Plot()
payload = dict(sx=3, sy=-2, x=10, y=100, delta=5)
test_callback = EventCallback(['sx','sy','x','y', 'delta'])
plot.on_event(events.MouseWheel, test_callback)
assert test_callback.event_name == None
plot._trigger_event(events.MouseWheel(plot, **payload))
assert test_callback.event_name == events.MouseWheel.event_name
assert test_callback.payload == payload
def test_pan_callbacks():
3
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_pan_callbacks():
plot = Plot()
payload = dict(sx=3, sy=-2, x=10, y=100, delta_x=2, delta_y=3.2)
test_callback = EventCallback(['sx','sy','x','y', 'delta_x', 'delta_y'])
plot.on_event(events.Pan, test_callback)
assert test_callback.event_name == None
plot._trigger_event(events.Pan(plot, **payload))
assert test_callback.event_name == events.Pan.event_name
assert test_callback.payload == payload
def test_pinch_callbacks():
0
View Source File : calendar.py
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
License : GNU Affero General Public License v3.0
Project Creator : andrewcooke
def __init__(self, df, scale=13, border_day=0.25, border_month=0.4, border_year=0.4, title=None,
hover=None, not_hover=tuple(), all_hover=False):
self._hover_args = (hover, not_hover, all_hover)
start, finish = df.index.min(), df.index.max()
start = dt.date(start.year, 1, 1)
finish = dt.date(finish.year + 1, 1, 1) - dt.timedelta(days=1)
delta_year = 7 * (1 + border_day) + border_year
self._df = df
self._df_all = pd.DataFrame(data={CALENDAR_SIZE: 1, CALENDAR_RADIUS: 0.5},
index=pd.date_range(start, finish))
self._set_date(self._df)
self._set_xy(self._df, start, finish, border_day, border_month, delta_year)
self._set_date(self._df_all)
self._set_xy(self._df_all, start, finish, border_day, border_month, delta_year)
xlo = self._df_all[CALENDAR_X].min()
xhi = self._df_all[CALENDAR_X].max()
ylo = self._df_all[CALENDAR_Y].min()
yhi = self._df_all[CALENDAR_Y].max()
nx = int(scale * (xhi - xlo))
ny = int(scale * (yhi - ylo))
plot = Plot(x_range=Range1d(xlo - 4, xhi + 4), y_range=Range1d(ylo - 1, yhi + 4),
width=nx, height=ny, title=Title(text=title))
self._add_labels(plot, start, finish, xlo, xhi, yhi, border_day, delta_year)
self._plot = plot
@staticmethod
0
View Source File : draw.py
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
def circuit_from(bqm):
G = bqm.to_networkx_graph()
plot = Plot(
plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)
)
plot.title.text = "Multiplication as a BQM"
plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
graph_renderer = from_networkx(G, circuit_layout)
circle_size = 25
graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB")
graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E")
graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C")
edge_size = 2
graph_renderer.edge_renderer.glyph = MultiLine(
line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size
)
graph_renderer.edge_renderer.selection_glyph = MultiLine(
line_color="#EEA64E", line_width=edge_size
)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
plot.background_fill_color = "#202239"
add_labels(plot)
show(Row(plot))
def frequency_of(results):
0
View Source File : draw.py
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
def draw(S, position=None, with_labels=False):
"""Plot the given signed social network.
Args:
S: The network
position (dict, optional):
The position for the nodes. If no position is provided, a layout will be calculated. If the nodes have
'color' attributes, a Kamanda-Kawai layout will be used to group nodes of the same color together.
Otherwise, a circular layout will be used.
Returns:
A dictionary of positions keyed by node.
Examples:
>>> import dwave_structural_imbalance_demo as sbdemo
>>> gssn = sbdemo.GlobalSignedSocialNetwork()
>>> nld_before = gssn.get_node_link_data('Syria', 2013)
>>> nld_after = gssn.solve_structural_imbalance('Syria', 2013)
# draw Global graph before solving; save node layout for reuse
>>> position = sbdemo.draw('syria.png', nld_before)
# draw the Global graph; reusing the above layout, and calculating a new grouped layout
>>> sbdemo.draw('syria_imbalance.png', nld_after, position)
>>> sbdemo.draw('syria_imbalance_grouped', nld_after)
"""
# we need a consistent ordering of the edges
edgelist = S.edges()
nodelist = S.nodes()
def layout_wrapper(S):
pos = position
if pos is None:
try:
# group bipartition if nodes are colored
dist = defaultdict(dict)
for u, v in product(nodelist, repeat=2):
if u == v: # node has no distance from itself
dist[u][v] = 0
elif (
nodelist[u]["color"] == nodelist[v]["color"]
): # make same color nodes closer together
dist[u][v] = 1
else: # make different color nodes further apart
dist[u][v] = 2
pos = nx.kamada_kawai_layout(S, dist)
except KeyError:
# default to circular layout if nodes aren't colored
pos = nx.circular_layout(S)
return pos
# call layout wrapper once with all nodes to store position for calls with partial graph
position = layout_wrapper(S)
plot = Plot(
plot_width=600, plot_height=400, x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2)
)
tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool()]
plot.add_tools(*tools)
plot.toolbar.active_scroll = tools[0]
def get_graph_renderer(S, line_dash):
# we need a consistent ordering of the edges
edgelist = S.edges()
nodelist = S.nodes()
# get the colors assigned to each edge based on friendly/hostile
sign_edge_color = ["#87DACD" if S[u][v]["sign"] == 1 else "#FC9291" for u, v in edgelist]
# get the colors assigned to each node by coloring
try:
coloring_node_color = [
"#4378F8" if nodelist[v]["color"] else "#FFE897" for v in nodelist
]
except KeyError:
coloring_node_color = ["#FFFFFF" for __ in nodelist]
graph_renderer = from_networkx(S, layout_wrapper)
circle_size = 10
graph_renderer.node_renderer.data_source.add(coloring_node_color, "color")
graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="color")
edge_size = 2
graph_renderer.edge_renderer.data_source.add(sign_edge_color, "color")
try:
graph_renderer.edge_renderer.data_source.add(
[S[u][v]["event_year"] for u, v in edgelist], "event_year"
)
graph_renderer.edge_renderer.data_source.add(
[S[u][v]["event_description"] for u, v in edgelist], "event_description"
)
plot.add_tools(
HoverTool(
tooltips=[("Year", "@event_year"), ("Description", "@event_description")],
line_policy="interp",
)
)
except KeyError:
pass
graph_renderer.edge_renderer.glyph = MultiLine(line_color="color", line_dash=line_dash)
graph_renderer.inspection_policy = EdgesAndLinkedNodes()
return graph_renderer
try:
S_dash = S.edge_subgraph(((u, v) for u, v in edgelist if S[u][v]["frustrated"]))
S_solid = S.edge_subgraph(((u, v) for u, v in edgelist if not S[u][v]["frustrated"]))
plot.renderers.append(get_graph_renderer(S_dash, "dashed"))
plot.renderers.append(get_graph_renderer(S_solid, "solid"))
except KeyError:
plot.renderers.append(get_graph_renderer(S, "solid"))
plot.background_fill_color = "#202239"
positions = layout_wrapper(S)
if with_labels:
data = {"xpos": [], "ypos": [], "label": []}
for label, pos in positions.items():
data["label"].append(label)
data["xpos"].append(pos[0])
data["ypos"].append(pos[1])
labels = LabelSet(
x="xpos",
y="ypos",
text="label",
level="glyph",
source=ColumnDataSource(data),
x_offset=-5,
y_offset=10,
text_color="#F5F7FB",
text_font_size="12pt",
)
plot.add_layout(labels)
show(Row(plot))
return positions
0
View Source File : plotting.py
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : FeatureLabs
def dendrogram(D, figargs=None):
'''Creates a dendrogram plot.
This plot can show full structure of a given dendrogram.
Args:
D (henchman.selection.Dendrogram): An initialized dendrogram object
Examples:
>>> from henchman.selection import Dendrogram
>>> from henchman.plotting import show
>>> import henchman.plotting as hplot
>>> D = Dendrogram(X)
>>> plot = hplot.dendrogram(D)
>>> show(plot)
'''
if figargs is None:
return lambda figargs: dendrogram(D, figargs=figargs)
G = nx.Graph()
vertices_source = ColumnDataSource(
pd.DataFrame({'index': D.columns.keys(),
'desc': list(D.columns.values())}))
edges_source = ColumnDataSource(
pd.DataFrame(D.edges[0]).rename(
columns={1: 'end', 0: 'start'}))
step_source = ColumnDataSource(
pd.DataFrame({'step': [0],
'thresh': [D.threshlist[0]],
'components': [len(D.graphs[0])]}))
G.add_nodes_from([str(x) for x in vertices_source.data['index']])
G.add_edges_from(zip(
[str(x) for x in edges_source.data['start']],
[str(x) for x in edges_source.data['end']]))
graph_renderer = from_networkx(G, nx.circular_layout,
scale=1, center=(0, 0))
graph_renderer.node_renderer.data_source = vertices_source
graph_renderer.node_renderer.view = CDSView(source=vertices_source)
graph_renderer.edge_renderer.data_source = edges_source
graph_renderer.edge_renderer.view = CDSView(source=edges_source)
plot = Plot(plot_width=400, plot_height=400,
x_range=Range1d(-1.1, 1.1),
y_range=Range1d(-1.1, 1.1))
plot.title.text = "Feature Connectivity"
graph_renderer.node_renderer.glyph = Circle(
size=5, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(
size=15, fill_color=Spectral4[2])
graph_renderer.edge_renderer.data_source = edges_source
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
line_alpha=0.6,
line_width=.5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(
line_color=Spectral4[2],
line_width=3)
graph_renderer.node_renderer.hover_glyph = Circle(
size=5,
fill_color=Spectral4[1])
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
plot.add_tools(
HoverTool(tooltips=[("feature", "@desc"),
("index", "@index"), ]),
TapTool(),
BoxZoomTool(),
SaveTool(),
ResetTool())
plot = _modify_plot(plot, figargs)
if figargs['static']:
return plot
def modify_doc(doc, D, figargs):
data_table = DataTable(source=step_source,
columns=[TableColumn(field='step',
title='Step'),
TableColumn(field='thresh',
title='Thresh'),
TableColumn(field='components',
title='Components')],
height=50, width=400)
def callback(attr, old, new):
try:
edges = D.edges[slider.value]
edges_source.data = ColumnDataSource(
pd.DataFrame(edges).rename(columns={1: 'end',
0: 'start'})).data
step_source.data = ColumnDataSource(
{'step': [slider.value],
'thresh': [D.threshlist[slider.value]],
'components': [len(D.graphs[slider.value])]}).data
except Exception as e:
print(e)
slider = Slider(start=0,
end=(len(D.edges) - 1),
value=0,
step=1,
title="Step")
slider.on_change('value', callback)
doc.add_root(column(slider, data_table, plot))
return lambda doc: modify_doc(doc, D, figargs)
def f1(X, y, model, n_precs=1000, n_splits=1, figargs=None):
0
View Source File : clustree.py
License : MIT License
Project Creator : ivirshup
License : MIT License
Project Creator : ivirshup
def gen_clustree_plot(
g: nx.Graph,
pos: dict = None,
plot_kwargs: dict = None,
node_kwargs: dict = None,
edge_kwargs: dict = None,
):
"""
Takes a graph, basically just instantiates a plot
Args:
g: clustree graph.
pos: dict containing calculated layout positions
"""
if pos is None:
pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
if plot_kwargs is None:
plot_kwargs = dict(plot_width=1000, plot_height=600)
if node_kwargs is None:
node_kwargs = dict(size=15)
if edge_kwargs is None:
edge_kwargs = dict(line_alpha="edge_alpha", line_width=1)
g_p = g.copy()
# set_edge_alpha(g_p)
plot = Plot(**get_ranges(pos), **plot_kwargs)
graph_renderer = from_networkx(g_p, pos)
graph_renderer.node_renderer.glyph = Circle(**node_kwargs)
graph_renderer.edge_renderer.glyph = MultiLine(**edge_kwargs)
plot.renderers.append(graph_renderer)
# node_hover = HoverTool(
# tooltips=[("solution_name", "@solution_name"),
# ("partition_id", "@partition_id"), ("n_items", "@n_items")]
# )
# plot.add_tools(node_hover)
return plot
def get_ranges(pos):
0
View Source File : clustree.py
License : MIT License
Project Creator : ivirshup
License : MIT License
Project Creator : ivirshup
def plot_hierarchy(
complist: "ComponentList", coords: pd.DataFrame, *, scatter_kwargs={}
):
"""
Params
------
complist
List of components that will be plotted in this graph.
"""
coords = coords.copy()
scatter_kwargs = scatter_kwargs.copy()
g = complist.to_graph()
assert len(list(nx.components.weakly_connected_components(g))) == 1
for k, v in make_umap_plots(
complist, coords, scatter_kwargs=scatter_kwargs
).items():
g.nodes[k]["img"] = v
pos = json_friendly(
nx.nx_agraph.graphviz_layout(nx.DiGraph(g.edges(data=False)), prog="dot")
)
graph_renderer = from_networkx(g, pos)
graph_renderer.node_renderer.glyph = Circle(size=15)
graph_renderer.edge_renderer.glyph = MultiLine(line_width=1)
node_hover = HoverTool(
tooltips=[
("img", "@img{safe}"),
("component_id", "@index"),
("# solutions:", "@n_solutions"),
("# samples in intersect", "@n_intersect"),
("# samples in union", "@n_union"),
],
attachment="vertical",
)
# Adding labels
label_src = pd.DataFrame.from_dict(
graph_renderer.layout_provider.graph_layout, orient="index", columns=["x", "y"]
)
label_src.index.name = "nodeid"
label_src = ColumnDataSource(label_src)
node_label = LabelSet(
x="x",
y="y",
text="nodeid",
level="annotation",
source=label_src,
text_align="center",
)
# layout = graph_renderer.layout_provider.graph_layout
# label, x, y = zip(*((str(label), x, y) for label, (x, y) in layout.items()))
# node_label = LabelSet(
# x=x, y=y, text=label, level="glyph"
# )
p = Plot(plot_width=1000, plot_height=500, **get_ranges(pos))
p.renderers.append(graph_renderer)
p.add_layout(node_label)
p.add_tools(node_hover, SaveTool())
return p
0
View Source File : visualization.py
License : GNU Affero General Public License v3.0
Project Creator : iza-institute-of-labor-economics
License : GNU Affero General Public License v3.0
Project Creator : iza-institute-of-labor-economics
def plot_dag(
functions,
targets=None,
columns_overriding_functions=None,
check_minimal_specification="ignore",
selectors=None,
labels=True,
tooltips=False,
plot_kwargs=None,
arrow_kwargs=None,
edge_kwargs=None,
label_kwargs=None,
node_kwargs=None,
):
"""Plot the dag of the tax and transfer system.
Parameters
----------
functions : str, pathlib.Path, callable, module, imports statements, dict
Functions can be anything of the specified types and a list of the same objects.
If the object is a dictionary, the keys of the dictionary are used as a name
instead of the function name. For all other objects, the name is inferred from
the function name.
targets : str, list of str
String or list of strings with names of functions whose output is actually
needed by the user.
columns_overriding_functions : str list of str
Names of columns in the data which are preferred over function defined in the
tax and transfer system.
check_minimal_specification : {"ignore", "warn", "raise"}, default "ignore"
Indicator for whether checks which ensure the most minimal configuration should
be silenced, emitted as warnings or errors.
selectors : str or list of str or dict or list of dict or list of str and dict
Selectors allow to you to select and de-select nodes in the graph for
visualization. For the full list of options, see the tutorial about
`visualization < ../docs/tutorials/visualize.ipynb>`_. By default, all nodes are
shown.
labels : bool, default True
Annotate nodes with labels.
tooltips : bool, default False
Experimental feature which makes the source code of the functions accessible as
a tooltip. Sometimes, the tooltip is not properly displayed.
plot_kwargs : dict
Additional keyword arguments passed to :class:`bokeh.models.Plot`.
arrow_kwargs : dict
Additional keyword arguments passed to :class:`bokeh.models.Arrow`. For example,
change the size of the head with ``{"size": 10}``.
edge_kwargs : dict
Additional keyword arguments passed to :class:`bokeh.models.MultiLine`. For
example, change the color with ``{"fill_color": "green"}``.
label_kwargs : dict
Additional keyword arguments passed to :class:`bokeh.models.LabelSet`. For
example, change the fontsize with ``{"text_font_size": "12px"}``.
node_kwargs : dict
Additional keyword arguments passed to :class:`bokeh.models.Circle`. For
example, change the color with ``{"fill_color": "orange"}``.
"""
targets = DEFAULT_TARGETS if targets is None else targets
targets = parse_to_list_of_strings(targets, "targets")
columns_overriding_functions = parse_to_list_of_strings(
columns_overriding_functions, "columns_overriding_functions"
)
# Load functions and perform checks.
functions, internal_functions = load_user_and_internal_functions(functions)
# Create one dictionary of functions and perform check.
functions = {**internal_functions, **functions}
functions = {
k: v for k, v in functions.items() if k not in columns_overriding_functions
}
_fail_if_targets_not_in_functions(functions, targets)
# Partial parameters to functions such that they disappear in the DAG.
functions = _mock_parameters_arguments(functions)
dag = create_dag(
functions, targets, columns_overriding_functions, check_minimal_specification
)
selectors = [] if selectors is None else _to_list(selectors)
plot_kwargs = {} if plot_kwargs is None else plot_kwargs
arrow_kwargs = {} if arrow_kwargs is None else arrow_kwargs
edge_kwargs = {} if edge_kwargs is None else edge_kwargs
label_kwargs = {} if label_kwargs is None else label_kwargs
node_kwargs = {} if node_kwargs is None else node_kwargs
dag = _select_nodes_in_dag(dag, selectors)
dag = _add_url_to_dag(dag)
# Even if we do not use the source codes as tooltips, we need to remove the
# functions.
dag = _replace_functions_with_source_code(dag)
plot_kwargs["title"] = _to_bokeh_title(
plot_kwargs.get("title", "Tax and Transfer System")
)
plot = Plot(**{**PLOT_KWARGS_DEFAULTS, **plot_kwargs})
layout = _create_pydot_layout(dag)
graph_renderer = from_networkx(dag, layout, scale=1, center=(0, 0))
graph_renderer.node_renderer.glyph = Circle(
**{**NODE_KWARGS_DEFAULTS, **node_kwargs}
)
graph_renderer.edge_renderer.visible = False
for (
_,
(start_node, end_node),
) in graph_renderer.edge_renderer.data_source.to_df().iterrows():
(x_start, y_start), (x_end, y_end) = _compute_arrow_coordinates(
layout[start_node], layout[end_node]
)
plot.add_layout(
Arrow(
end=NormalHead(**{**ARROW_KWARGS_DEFAULTS, **arrow_kwargs}),
x_start=x_start,
y_start=y_start,
x_end=x_end,
y_end=y_end,
**{**EDGE_KWARGS_DEFAULTS, **edge_kwargs},
)
)
plot.renderers.append(graph_renderer)
tools = [BoxZoomTool(), ResetTool()]
tools.append(TapTool(callback=OpenURL(url="@url")))
if tooltips:
tools.append(HoverTool(tooltips=TOOLTIPS))
plot.add_tools(*tools)
if labels:
source = ColumnDataSource(
pd.DataFrame(layout).T.rename(columns={0: "x", 1: "y"})
)
labels = LabelSet(
x="x",
y="y",
text="index",
source=source,
**{**LABEL_KWARGS_DEFAULT, **label_kwargs},
)
plot.add_layout(labels)
output_notebook()
show(plot)
return plot
def _mock_parameters_arguments(functions):
0
View Source File : visualize_utils.py
License : MIT License
Project Creator : ratsgo
License : MIT License
Project Creator : ratsgo
def visualize_self_attention_scores(tokens, scores, filename="/notebooks/embedding/self-attention.png",
use_notebook=False):
mean_prob = np.mean(scores)
weighted_edges = []
for idx_1, token_prob_dist_1 in enumerate(scores):
for idx_2, el in enumerate(token_prob_dist_1):
if idx_1 == idx_2 or el < mean_prob:
weighted_edges.append((tokens[idx_1], tokens[idx_2], 0))
else:
weighted_edges.append((tokens[idx_1], tokens[idx_2], el))
max_prob = np.max([el[2] for el in weighted_edges])
weighted_edges = [(el[0], el[1], (el[2] - mean_prob) / (max_prob - mean_prob)) for el in weighted_edges]
G = nx.Graph()
G.add_nodes_from([el for el in tokens])
G.add_weighted_edges_from(weighted_edges)
plot = Plot(plot_width=500, plot_height=500,
x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
graph_renderer.node_renderer.data_source.data['colors'] = Spectral8[:len(tokens)]
graph_renderer.node_renderer.glyph = Circle(size=15, line_color=None, fill_color="colors")
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="colors")
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="grey")
graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a, b)['weight'] * 3 for a, b in
G.edges()]
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_width={'field': 'line_width'})
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="grey", line_width=5)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="grey", line_width=5)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()
plot.renderers.append(graph_renderer)
x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
data = {'x': list(x), 'y': list(y), 'connectionNames': tokens}
source = ColumnDataSource(data)
labels = LabelSet(x='x', y='y', text='connectionNames', source=source, text_align='center')
plot.renderers.append(labels)
plot.add_tools(SaveTool())
if use_notebook:
output_notebook()
show(plot)
else:
export_png(plot, filename)
print("save @ " + filename)
def visualize_words(words, vecs, palette="Viridis256", filename="/notebooks/embedding/words.png",
0
View Source File : test_properties.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_HasProps_clone():
p1 = Plot(plot_width=1000)
c1 = p1.properties_with_values(include_defaults=False)
p2 = p1._clone()
c2 = p2.properties_with_values(include_defaults=False)
assert c1 == c2
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
Test___all__ = verify_all(bcp, ALL)
0
View Source File : test_query.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def large_plot():
source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1]))
xdr = Range1d(start=0, end=1)
xdr.tags.append("foo")
xdr.tags.append("bar")
ydr = Range1d(start=10, end=20)
ydr.tags.append("foo")
ydr.tags.append(11)
plot = Plot(x_range=xdr, y_range=ydr)
ydr2 = Range1d(start=0, end=100)
plot.extra_y_ranges = {"liny": ydr2}
circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black")
plot.add_glyph(source, circle, name="mycircle")
line = Line(x="x", y="y")
plot.add_glyph(source, line, name="myline")
rect = Rect(x="x", y="y", width=1, height=1, fill_color="green")
plot.add_glyph(source, rect, name="myrect")
plot.add_layout(DatetimeAxis(), 'below')
plot.add_layout(LogAxis(), 'left')
plot.add_layout(LinearAxis(y_range_name="liny"), 'left')
plot.add_layout(Grid(dimension=0), 'left')
plot.add_layout(Grid(dimension=1), 'left')
plot.add_tools(
BoxZoomTool(), PanTool(), SaveTool(), ResetTool(), WheelZoomTool(),
)
return plot
plot = large_plot()
0
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_buttonclick_constructor_plot():
with pytest.raises(ValueError):
events.ButtonClick(Plot())
def test_lodstart_constructor_button():
0
View Source File : test_events.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_pinch_callbacks():
plot = Plot()
payload = dict(sx=3, sy=-2, x=10, y=100, scale=42)
test_callback = EventCallback(['sx','sy','x','y', 'scale'])
plot.on_event(events.Pinch, test_callback)
assert test_callback.event_name == None
plot._trigger_event(events.Pinch(plot, **payload))
assert test_callback.event_name == events.Pinch.event_name
assert test_callback.payload == payload
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
0
View Source File : test_objects.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def large_plot(n):
from bokeh.models import (
Plot, LinearAxis, Grid, GlyphRenderer,
ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool,
BoxSelectTool, SaveTool, ResetTool
)
from bokeh.models.layouts import Column
from bokeh.models.glyphs import Line
col = Column()
objects = set([col])
for i in xrange(n):
source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
xdr = DataRange1d()
ydr = DataRange1d()
plot = Plot(x_range=xdr, y_range=ydr)
xaxis = LinearAxis()
plot.add_layout(xaxis, "below")
yaxis = LinearAxis()
plot.add_layout(yaxis, "left")
xgrid = Grid(dimension=0)
plot.add_layout(xgrid, "center")
ygrid = Grid(dimension=1)
plot.add_layout(ygrid, "center")
tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter]
glyph = Line(x='x', y='y')
renderer = GlyphRenderer(data_source=source, glyph=glyph)
plot.renderers.append(renderer)
pan = PanTool()
zoom_in = ZoomInTool()
zoom_out = ZoomOutTool()
wheel_zoom = WheelZoomTool()
box_zoom = BoxZoomTool()
box_select = BoxSelectTool()
save = SaveTool()
reset = ResetTool()
tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset]
plot.add_tools(*tools)
col.children.append(plot)
objects |= set([
xdr, ydr,
xaxis, yaxis,
xgrid, ygrid,
renderer, renderer.view, glyph,
source, source.selected, source.selection_policy,
plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title,
box_zoom.overlay, box_select.overlay,
] + tickers + tools)
return col, objects
class TestMetaModel(object):