Here are the examples of the python api bokeh.models.Circle taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
17 Examples
3
View Source File : search_tree_visualization.py
License : GNU General Public License v3.0
Project Creator : aI-lab-glider
License : GNU General Public License v3.0
Project Creator : aI-lab-glider
def show_results(self):
layout = self.hierarchy_pos(self.G, 0, x_range=(-50000, 100000), y_range=(-100000, 100000))
graph_renderer = from_networkx(self.G, layout, scale=1, center=layout[0])
graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.node_renderer.data_source.add([' < i>italics < /i>'] * self.N, 'fonts')
graph_renderer.node_renderer.data_source.add(self.imgs, 'imgs')
self.plot.renderers.append(graph_renderer)
show(self.plot)
def update_graph(self, node):
3
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 _circle(self, df, fill_alpha=CALENDAR_FILL, line_alpha=CALENDAR_ALPHA, color=CALENDAR_COLOR):
circle = Circle(x=CALENDAR_X, y=CALENDAR_Y, radius=CALENDAR_RADIUS,
fill_color=color, fill_alpha=fill_alpha,
line_color=color, line_alpha=line_alpha)
return self._plot.add_glyph(ColumnDataSource(df), circle, name='with_hover' if df is self._df else None)
def _arc(self, df, line_alpha=CALENDAR_ALPHA, color=CALENDAR_COLOR):
3
View Source File : test_renderers.py
License : MIT License
Project Creator : rthorst
License : MIT License
Project Creator : rthorst
def test_graphrenderer_check_malformed_graph_source_no_node_index():
node_source = ColumnDataSource()
node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle())
renderer = GraphRenderer(node_renderer=node_renderer)
check = renderer._check_malformed_graph_source()
assert check != []
def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end():
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 : BuildACell
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell
def graphPlot(DG,DGspecies,DGreactions,plot,layout="force",positions=None,plot_species = True, plot_reactions = True, plot_edges = True, plot_arrows = True,\
species_glyph_size = 12, reaction_glyph_size = 8, posscale = 1.0,layoutfunc=None,iterations=2000,rseed=30,show_species_images=False):
"""given a directed graph, plot it!
Inputs:
DG: a directed graph of type DiGraph
DGspecies: a directed graph which only contains the species nodes
DGreactions: a directed graph which only contains the reaction nodes
plot: a bokeh plot object
layout: graph layout function.
'force' uses fa2 to push nodes apart
'circle' plots the nodes and reactions in two overlapping circles, with the reactions on the inside of the circle
'custom' allows user input "layoutfunc". Internally, layoutfunc is passed the three inputs (DG, DGspecies, DGreactions)
and should output a position dictionary with node { < node number>:(x,y)}
positions: a dictionary of node names and x,y positions. this gets passed into the layout function
posscale: multiply the scaling of the plot. This only affects the arrows because the arrows are a hack :("""
random.seed(rseed)
if(not PLOT_NETWORK):
warn("network plotting disabled because some libraries are not found")
return
if(layout == "force"):
# below are parameters for the force directed graph visualization
forceatlas2 = ForceAtlas2(
# Behavior alternatives
outboundAttractionDistribution=True, # Dissuade hubs
linLogMode=False, # NOT IMPLEMENTED
# Prevent overlap (NOT IMPLEMENTED)
adjustSizes=False,
edgeWeightInfluence=1.0,
# Performance
jitterTolerance=1.0, # Tolerance
barnesHutOptimize=True,
barnesHutTheta=1.2,
multiThreaded=False, # NOT IMPLEMENTED
# Tuning
scalingRatio=2.4*posscale,
strongGravityMode=False,
gravity=1.0,
# Log
verbose=False)
positions = forceatlas2.forceatlas2_networkx_layout(
DG, pos=positions, iterations=iterations)
elif(layout == "circle"):
positions = nx.circular_layout(DGspecies, scale=50*posscale)
positions.update(nx.circular_layout(DGreactions, scale=35*posscale))
elif(layout == "custom"):
positions = layoutfunc(DG, DGspecies, DGreactions)
reaction_renderer = from_networkx(DGreactions, positions, center=(0, 0))
species_renderer = from_networkx(DGspecies, positions, center=(0, 0))
edges_renderer = from_networkx(DG, positions, center=(0, 0))
#Set xbounds and ybounds:
xbounds = [0, 0]
ybounds = [0, 0]
for n in positions:
xbounds[0] = min([xbounds[0], positions[n][0]])
xbounds[1] = max([xbounds[1], positions[n][0]])
ybounds[0] = min([ybounds[0], positions[n][1]])
ybounds[1] = max([ybounds[1], positions[n][1]])
max_glyph = max([reaction_glyph_size, species_glyph_size])
xbounds[0] -= max_glyph
xbounds[1] += max_glyph
ybounds[0] -= max_glyph
ybounds[1] += max_glyph
# edges
edges_renderer.node_renderer.glyph = Circle(
size=species_glyph_size, line_alpha=0, fill_alpha=0, fill_color="color")
edges_renderer.edge_renderer.glyph = MultiLine(
line_alpha=0.2, line_width=4, line_join="round", line_color="color")
edges_renderer.edge_renderer.selection_glyph = MultiLine(
line_color=Spectral4[2], line_width=5, line_join="round")
edges_renderer.edge_renderer.hover_glyph = MultiLine(
line_color=Spectral4[1], line_width=5, line_join="round")
if plot_arrows:
xbounds_a, ybounds_a = makeArrows2(
edges_renderer, DG, positions, headsize=5) # make the arrows!
xbounds[0] = min([xbounds[0], xbounds_a[0]])
xbounds[1] = max([xbounds[1], xbounds_a[1]])
ybounds[0] = min([ybounds[0], ybounds_a[0]])
ybounds[1] = max([ybounds[1], ybounds_a[1]])
# we want to find the middle of the graph and plot a square that is 1:1 aspect ratio
# find the midpoint of the graph
xmid = statistics.mean(xbounds)
ymid = statistics.mean(ybounds)
# now, subtract the middle from the edges
xmiddlized = [a-xmid for a in xbounds]
ymiddlized = [a-ymid for a in ybounds]
# now, find the biggest dimension
absdim = max([abs(a) for a in xmiddlized+ymiddlized])
xlim = [xmid-absdim*1.05, xmid + absdim*1.05]
ylim = [ymid-absdim*1.05, ymid + absdim*1.05]
# now set it on the plot!
plot.x_range = Range1d(xlim[0], xlim[1])
plot.y_range = Range1d(ylim[0], ylim[1])
# reactions
reaction_renderer.node_renderer.glyph = Square(
size=reaction_glyph_size, fill_color="color")
reaction_renderer.node_renderer.selection_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[2])
reaction_renderer.node_renderer.hover_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[1])
# nodes
species_renderer.node_renderer.glyph = Circle(size=12, fill_color="color")
species_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
species_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
#this part adds the interactive elements that make it so that the lines are highlighted
#when you mouse over and click
edge_hover_tool = HoverTool(tooltips= None,renderers=[edges_renderer])
if( not show_species_images):
species_hover_tool = HoverTool(tooltips=[("name", "@species"), ("type", "@type")],\
renderers=[species_renderer],attachment="right")
else:
species_hover_tool = HoverTool(tooltips=' < div> < div> < img src="data:image/png;base64,@image" style="float: left; margin: 0px 0px 0px 0px;"> < /img> < /div> < /div>',\
renderers=[species_renderer],attachment="right")
rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
renderers=[reaction_renderer],attachment="right")
plot.add_tools(edge_hover_tool,species_hover_tool,rxn_hover_tool, TapTool(), BoxSelectTool(),PanTool(),WheelZoomTool())
edges_renderer.selection_policy = NodesAndLinkedEdges()
edges_renderer.inspection_policy = EdgesAndLinkedNodes()
if plot_edges:
plot.renderers.append(edges_renderer)
if plot_reactions:
plot.renderers.append(reaction_renderer)
if plot_species:
plot.renderers.append(species_renderer)
def generate_networkx_graph(CRN,useweights=False,use_pretty_print=False,pp_show_material=True,
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 : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getLapFigure(p1, df_, ds, mode, ref=False, hasref=False):
# add required colors to dataframe and create datasource
df_ = color_mode_map[mode](df_, ref)
to_bokeh = lambda c: list(map(mplcolors.to_hex, c))
x = 'xr' if ref else 'x'
y = 'yr' if ref else 'y'
color = 'color_%s'%((mode+'_r') if ref else mode)
ds.data[color] = to_bokeh(df_[color])
# shift the reference points to the outside
if ref:
ds.data[x] += 30*np.cos(df_.heading+np.pi/2)
ds.data[y] += 30*np.sin(df_.heading+np.pi/2)
# plot the track map, overwrite the (non)selection glyph to keep our color from ds
# the hover effect is configured below
r2 = p1.scatter(x=x, y=y, source=ds, color=color)
r2.nonselection_glyph = r2.selection_glyph
if ref: return p1
# add some lap descriptions
corners = acctelemetry.corners(df_)
corners_ds = ColumnDataSource(dict(
x=df_.x.values[corners],
y=df_.y.values[corners],
text=['T%i'%i for i in range(1, len(corners)+1)],
))
labels = LabelSet(x='x', y='y', text='text', level='glyph',
x_offset=5, y_offset=5,
source=corners_ds, render_mode='canvas')
p1.add_layout(labels)
# create a invisible renderer for the track map
# this is used to trigger the hover, thus the size is large
c1 = p1.circle(x='x', y='y', source=ds, size=10, fill_alpha=0.0, alpha=0.0)
c1.selection_glyph = Circle(fill_color='red', fill_alpha=.7, line_color=None)
c1.nonselection_glyph = Circle(fill_alpha=0, line_color=None)
# create a renderer to show a dot for the reference
if hasref:
cr = p1.circle(x='xr', y='yr', source=ds,
size = 8 if mode in ['absolut', 'gainloss'] else 10,
fill_alpha=0.0, alpha=0.0)
cr.selection_glyph = Circle(fill_color='blue', fill_alpha=.7, line_color=None)
cr.nonselection_glyph = Circle(fill_alpha=0, line_color=None)
return c1
def getLapSlider(ds, p0, r0, hover0, view):
0
View Source File : figures.py
License : GNU General Public License v3.0
Project Creator : gotzl
License : GNU General Public License v3.0
Project Creator : gotzl
def getTrackMap(target, reference=None, mode='speed', view='lapsdelta'):
if reference is None:
df_, df_r = target, None
else:
df_, df_r = acctelemetry.lapdelta(reference, target)
ds = ColumnDataSource(df_)
p0 = figure(plot_height=400, plot_width=800,
tools="crosshair,pan,reset,save,wheel_zoom")
colors = itertools.cycle(palette)
col0, col1 = next(colors), next(colors)
# create the velo vs dist plot
r0 = p0.line(x='dist_lap', y='speedkmh', source=ds, color=col0, line_width=2)
# overwrite the (non)selection glyphs with the base line style
# the style for the hover will be set below
nonselected_ = Line(line_alpha=1, line_color=col0, line_width=2)
r0.selection_glyph = nonselected_
r0.nonselection_glyph = nonselected_
if reference is not None:
# create the dt vs dist plot with extra y axis, set the (non)selection glyphs
lim = max(df_.dt.abs())
lim += lim*.2
p0.extra_y_ranges = {"dt": Range1d(start=-lim, end=lim)}
p0.add_layout(LinearAxis(
y_range_name='dt',
axis_label='dt [s]'), 'right')
r1 = p0.line(x='dist_lap', y='dt', source=ds, y_range_name='dt', color=col1, line_width=2)
r1.selection_glyph = Line(line_alpha=1, line_color='red', line_width=5)
r1.nonselection_glyph = Line(line_alpha=1, line_color=col1, line_width=2)
# create reference velo vs dist plot
p0.line(df_r.dist_lap, df_r.speedkmh, color=next(colors), line_width=2)
# create an invisible renderer for velo vs dist
# this is used to trigger the hover, thus the size is large
c0 = p0.circle(x='dist_lap', y='speedkmh', source=ds, size=10, fill_alpha=0.0, alpha=0.0)
c0.selection_glyph = Circle(fill_color='red', fill_alpha=1., line_color=None)
c0.nonselection_glyph = Circle(fill_alpha=0, line_color=None)
# create figure for track map
p1 = figure(plot_height=400, plot_width=800, tools="crosshair,pan,reset,save,wheel_zoom")
# create map of the track
c1 = getLapFigure(p1, df_, ds, mode, hasref=(reference is not None))
# add some lap tangents to guide the eye when comparing map and refmap
if reference is not None and mode not in ['absolut', 'gainloss']:
x0 = df_.x.values
y0 = df_.y.values
h = df_.heading.values
x1 = x0 + 30*np.cos(h+np.pi/2)
y1 = y0 + 30*np.sin(h+np.pi/2)
p1.segment(x0=x0, y0=y0, x1=x1, y1=y1, color="#F4A582", line_width=1)
# calculate points for the reference map drawn 'outside' of the other track map
getLapFigure(p1, df_, ds , mode, ref=True)
# Toooltips that show some information for each point, triggered via slider.onchange JS
tools = ['time','dist','speedkmh']
if reference is not None:
tools.append('speedkmh_r')
if mode not in ['absolut', 'gainloss', 'pedals', 'speed']:
tools.extend([mode, '%s_r'%mode])
elif mode in ['pedals']:
tools.extend(['throttle', 'throttle_r', 'brake', 'brake_r'])
tools.append('dt')
elif mode == 'pedals':
tools.extend(['throttle', 'brake'])
elif mode != 'speed':
tools.append(mode)
hover0 = createHoverTool(tools)
# a small hack to show only one tooltip (hover selects multiple points)
# TODO: doesn't work anymore with recent bokeh
# hover0.tooltips[-1] = (hover0.tooltips[-1][0], hover0.tooltips[-1][1]+"""
# < style>
# .bk-tooltip>div:not(:first-child) {display:none;}
# < /style>""")
hover0.renderers = [r0]
hover0.mode = 'vline'
hover0.line_policy='interp'
# selection change via button and slider. Tooltips 'hover0' will be rendered in 'p0' using rederer 'r0'
slider = getLapSlider(ds, p0, r0, hover0, view=view)
btns = getLapControls(ds, slider)
# Hovertools, that emit a selection change by modifying the slider value
callback = CustomJS(args=dict(slider=slider), code=
"""
let val = cb_data['index'].indices[0]
if (val!=0 && !isNaN(val))
slider.value = cb_data['index'].indices[0];
""")
p0.add_tools(HoverTool(tooltips=None, renderers=[c0],
callback=callback,
line_policy='interp', mode='vline'))
p1.add_tools(HoverTool(tooltips=None, renderers=[c1],
callback=callback,
line_policy='interp', mode='mouse', point_policy='snap_to_data'))
p0.add_tools(hover0)
# p1.add_tools(hover1)
return column(btns, slider, p0, p1, sizing_mode='scale_width')
def getTrackMapPanel(df):
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 : showMatLabFig._spatioTemporal.py
License : MIT License
Project Creator : richieBao
License : MIT License
Project Creator : richieBao
def interactiveG(G):
from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.io import output_notebook, show
output_notebook()
# We could use figure here but don't want all the axes and titles
#plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
output_file("PHMI_network")
source=ColumnDataSource(data=dict(
x=locations[0].tolist(),
#x=[idx for idx in range(len(PHMIList))],
#y=locations[1].tolist(),
y=PHMIList,
#desc=[str(i) for i in PHMIList],
#PHMI_value=PHMI_dic[0][0].tolist(),
))
TOOLTIPS=[
("index", "$index"),
("(x,y)", "($x, $y)"),
#("desc", "@desc"),
#("PHMI", "$PHMI_value"),
]
plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
#G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))
#plot.renderers.append(graph)
fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
graph.layout_provider = fixed_layout_provider
plot.renderers.append(graph)
# Blue circles for nodes, and light grey lines for edges
graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')
graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)
# green hover for both nodes and edges
graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')
graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)
# When we hover over nodes, highlight adjecent edges too
graph.inspection_policy = NodesAndLinkedEdges()
plot.add_tools(HoverTool(tooltips=None))
colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
ScalePhmi=math.pow(10,1)
i=0
for val,idx in zip(phmi_breakPtsNeg, plot_x):
plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
i+=1
show(plot)
#06-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d
def colorMesh_phmi(landmarks,locations,targetPts_idx,Phmi):
0
View Source File : driverlessCityProject_spatialPointsPattern_association_basic.py
License : MIT License
Project Creator : richieBao
License : MIT License
Project Creator : richieBao
def interactiveG(G):
from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.io import output_notebook, show
output_notebook()
# We could use figure here but don't want all the axes and titles
#plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
output_file("PHMI_network")
source=ColumnDataSource(data=dict(
x=locations[0].tolist(),
#x=[idx for idx in range(len(PHMIList))],
#y=locations[1].tolist(),
y=PHMIList,
#desc=[str(i) for i in PHMIList],
#PHMI_value=PHMI_dic[0][0].tolist(),
))
TOOLTIPS=[
("index", "$index"),
("(x,y)", "($x, $y)"),
#("desc", "@desc"),
#("PHMI", "$PHMI_value"),
]
plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
#G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))
#plot.renderers.append(graph)
fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
graph.layout_provider = fixed_layout_provider
plot.renderers.append(graph)
# Blue circles for nodes, and light grey lines for edges
graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')
graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)
# green hover for both nodes and edges
graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')
graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)
# When we hover over nodes, highlight adjecent edges too
graph.inspection_policy = NodesAndLinkedEdges()
plot.add_tools(HoverTool(tooltips=None))
colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
ScalePhmi=math.pow(10,1)
i=0
for val,idx in zip(phmi_breakPtsNeg, plot_x):
plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
i+=1
show(plot)
#05-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d
def colorMesh_phmi(landmarks,locations,targetPts_idx,Phmi):
0
View Source File : plots.py
License : Apache License 2.0
Project Creator : scaleoutsystems
License : Apache License 2.0
Project Creator : scaleoutsystems
def make_single_node_plot(self):
"""
Plot single node graph with reducer
:return: Bokeh plot with the graph
:rtype: bokeh.plotting.figure.Figure
"""
HOVER_TOOLTIPS = [
("Name", "@name"),
("Role", "@role"),
("Status", "@status"),
("Id", "@index"),
]
G = networkx.Graph()
G.add_node("reducer", adjusted_node_size=20, role='reducer',
status='active',
name='reducer',
color_by_this_attribute=Spectral8[0])
network_graph = from_networkx(G, networkx.spring_layout)
network_graph.node_renderer.glyph = Circle(size=20, fill_color = Spectral8[0])
network_graph.node_renderer.hover_glyph = Circle(size=20, fill_color='white',
line_width=2)
network_graph.node_renderer.selection_glyph = Circle(size=20,
fill_color='white', line_width=2)
plot = figure(tooltips=HOVER_TOOLTIPS, tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
width=725, height=460, sizing_mode='stretch_width',
x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))
plot.renderers.append(network_graph)
plot.axis.visible = False
plot.grid.visible = False
plot.outline_line_color = None
label = Label(x=0, y=0, text='reducer',
background_fill_color='#4bbf73', text_font_size='15px',
background_fill_alpha=.7, x_offset=-20, y_offset=10)
plot.add_layout(label)
return plot
def make_netgraph_plot(self, df, df_nodes):
0
View Source File : plots.py
License : Apache License 2.0
Project Creator : scaleoutsystems
License : Apache License 2.0
Project Creator : scaleoutsystems
def make_netgraph_plot(self, df, df_nodes):
"""
Create FEDn network visualization.
:param df: pandas dataframe with defined edges
:type df: pandas.Dataframe
:param df_nodes:pandas dataframe with defined nodes
:type df_nodes: pandas.Dataframe
:return: Bokeh plot with the graph
:rtype: bokeh.plotting.figure.Figure
"""
if df.empty:
#no combiners and thus no clients, plot only reducer
plot = self.make_single_node_plot()
return plot
G = networkx.from_pandas_edgelist(df, 'source', 'target', create_using=networkx.Graph())
degrees = dict(networkx.degree(G))
networkx.set_node_attributes(G, name='degree', values=degrees)
number_to_adjust_by = 20
adjusted_node_size = dict([(node, degree + number_to_adjust_by) for node, degree in networkx.degree(G)])
networkx.set_node_attributes(G, name='adjusted_node_size', values=adjusted_node_size)
# community
from networkx.algorithms import community
communities = community.greedy_modularity_communities(G)
# Create empty dictionaries
modularity_class = {}
modularity_color = {}
# Loop through each community in the network
for community_number, community in enumerate(communities):
# For each member of the community, add their community number and a distinct color
for name in community:
modularity_class[name] = community_number
modularity_color[name] = Spectral8[community_number]
# Add modularity class and color as attributes from the network above
networkx.set_node_attributes(G, modularity_class, 'modularity_class')
networkx.set_node_attributes(G, modularity_color, 'modularity_color')
node_role = {k:v for k,v in zip(df_nodes.id, df_nodes.role)}
networkx.set_node_attributes(G, node_role, 'role')
node_status = {k:v for k,v in zip(df_nodes.id, df_nodes.status)}
networkx.set_node_attributes(G, node_status, 'status')
node_name = {k:v for k,v in zip(df_nodes.id, df_nodes.name)}
networkx.set_node_attributes(G, node_name, 'name')
# Choose colors for node and edge highlighting
node_highlight_color = 'white'
edge_highlight_color = 'black'
# Choose attributes from G network to size and color by — setting manual
# size (e.g. 10) or color (e.g. 'skyblue') also allowed
size_by_this_attribute = 'adjusted_node_size'
color_by_this_attribute = 'modularity_color'
# Establish which categories will appear when hovering over each node
HOVER_TOOLTIPS = [
("Name", "@name"),
("Role", "@role"),
("Status", "@status"),
("Id", "@index"),
]
# Create a plot — set dimensions, toolbar, and title
plot = figure(tooltips=HOVER_TOOLTIPS,
tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
width=725, height=460, sizing_mode='stretch_width',
x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))
# Create a network graph object
# https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.drawing.layout.spring_layout.html
# if one like lock reducer add args: pos={'reducer':(0,1)}, fixed=['reducer']
network_graph = from_networkx(G, networkx.spring_layout, scale=1, center=(0, 0), seed=45)
# Set node sizes and colors according to node degree (color as category from attribute)
network_graph.node_renderer.glyph = Circle(size=size_by_this_attribute, fill_color=color_by_this_attribute)
# Set node highlight colors
network_graph.node_renderer.hover_glyph = Circle(size=size_by_this_attribute, fill_color=node_highlight_color,
line_width=2)
network_graph.node_renderer.selection_glyph = Circle(size=size_by_this_attribute,
fill_color=node_highlight_color, line_width=2)
# Set edge opacity and width
network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)
# Set edge highlight colors
network_graph.edge_renderer.selection_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)
network_graph.edge_renderer.hover_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)
# Highlight nodes and edges
network_graph.selection_policy = NodesAndLinkedEdges()
network_graph.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(network_graph)
#Node labels, red if status is offline, green is active
x, y = zip(*network_graph.layout_provider.graph_layout.values())
node_names = list(G.nodes(data='name'))
node_status = list(G.nodes(data='status'))
idx_offline = []
idx_online = []
node_labels = []
for e, n in enumerate(node_names):
if node_status[e][1] == 'active':
idx_online.append(e)
else:
idx_offline.append(e)
node_labels.append(n[1])
source_on = ColumnDataSource({'x': numpy.asarray(x)[idx_online], 'y': numpy.asarray(y)[idx_online], 'name': numpy.asarray(node_labels)[idx_online]})
labels = LabelSet(x='x', y='y', text='name', source=source_on, background_fill_color='#4bbf73', text_font_size='15px',
background_fill_alpha=.7, x_offset=-20, y_offset=10)
plot.renderers.append(labels)
source_off = ColumnDataSource({'x': numpy.asarray(x)[idx_offline], 'y': numpy.asarray(y)[idx_offline], 'name': numpy.asarray(node_labels)[idx_offline]})
labels = LabelSet(x='x', y='y', text='name', source=source_off, background_fill_color='#d9534f', text_font_size='15px',
background_fill_alpha=.7, x_offset=-20, y_offset=10)
plot.renderers.append(labels)
plot.axis.visible = False
plot.grid.visible = False
plot.outline_line_color = None
return plot