y_range=(-np.sqrt(3) / 2 - 0.7, 0.5), tools='', toolbar_location=None) plot.grid.grid_line_color = None plot.axis.visible = False plot.grid.grid_line_color = None plot.axis.visible = False plot.add_tools(HoverTool(tooltips=None), TapTool()) graph = GraphRenderer() state_size = 60 graph.node_renderer.data_source.add(node_indices, 'index') graph.node_renderer.glyph = Circle(size=state_size, fill_color='white', line_width=4) graph.node_renderer.selection_glyph = Circle(size=state_size, fill_color='red', line_width=4) graph.node_renderer.hover_glyph = Circle(size=state_size, fill_color='pink', line_width=4) graph.edge_renderer.glyph = MultiLine(line_color="black", line_width=2) graph.edge_renderer.selection_glyph = MultiLine(line_color='pink', line_width=2) graph.edge_renderer.hover_glyph = MultiLine(line_color='red', line_width=2) ### start of layout code x = [0, .7, 0.35]
def create(self): print("running create...") manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True, width=1300) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(self.source, cty_glyph) hwy = plot.add_glyph(self.source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) controls = WidgetBox(manufacturer_select, model_select, transmission_select, drive_select, class_select) top_panel = Row(controls, plot) layout = Column(top_panel, data_table) return layout
from bokeh.io import save from bokeh.models import Circle, LinearAxis, Plot, Range1d template =""" {% block preamble %} <style> body { background-color: lightblue; } </style> {% endblock %} """ plot = Plot(plot_width=600, plot_height=600, x_range=Range1d(0, 10), y_range=Range1d(0, 10), toolbar_location=None) # This is the no-fill that we're testing plot.background_fill_color = None plot.border_fill_color = None plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff')) plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff')) yaxis = LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="40px") plot.add_layout(yaxis, 'left') xaxis = LinearAxis(major_label_text_color='#ffffff', major_label_text_font_size="40px") plot.add_layout(xaxis, 'below') save(plot, template=template)
def generate_graph_internal_link_interactive(website, maximum): domain = urllib.parse.urlparse(website).netloc urls = add_edge({}, website, domain, maximum) # Generating graph and dict of degrees g = nx.Graph(urls) d = dict(g.degree) # Adding table table = dict(url=[k for k, v in d.items()], count=[v for k, v in d.items()]) source = ColumnDataSource(table) columns = [ TableColumn(field="url", title="URL"), TableColumn(field="count", title="Count"), ] data_table = DataTable(source=source, columns=columns, width=400, height_policy="max") # Generating node size and color maxi = 1 if len(d.values()) > 0: maxi = max(d.values()) node_size = {k: max(5, math.ceil((v / maxi) * 30)) for k, v in d.items()} node_color = {k: v for k, v in d.items()} mapper = linear_cmap(field_name='node_color', palette=Spectral6, low=min(node_color.values()), high=max(node_color.values())) nx.set_node_attributes(g, d, 'connection') nx.set_node_attributes(g, node_size, "node_size") nx.set_node_attributes(g, node_color, "node_color") plot = figure(title="Maillage Interne " + domain, plot_width=1200, plot_height=800, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1), sizing_mode='stretch_both') p = row([data_table, plot]) graph = from_networkx(g, nx.spring_layout, scale=2) node_hover_tool = HoverTool( tooltips=[("urls", "@index"), ("Connection", "@connection")]) plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool()) plot.toolbar.active_scroll = "auto" graph.node_renderer.hover_glyph = Circle(size=20, fill_color=Spectral4[1]) graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral8[6], line_width=1) graph.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=0.03) graph.node_renderer.glyph = Circle(size='node_size', fill_color=mapper) graph.inspection_policy = NodesAndLinkedEdges() color_bar = ColorBar(color_mapper=mapper['transform'], width=8, location=(0, 0)) plot.add_layout(color_bar, 'right') plot.renderers.append(graph) return p, domain
x = linspace(-2 * pi, 2 * pi, N) y = sin(x) * exp(-x) # Create an array of synthetic times, starting at the current time, and extending 24hrs times = (linspace(0, 24 * 3600, N) + time.time()) * 1000 source = ColumnDataSource(data=dict(x=x, y=y, times=times)) plot = Plot(min_border=80, width=800, height=350, background_fill_color="#efefef") circle = Circle(x="times", y="y", fill_color="red", size=3, line_color=None, fill_alpha=0.5) plot.add_glyph(source, circle) plot.add_layout(DatetimeAxis(), 'below') plot.add_layout(DatetimeAxis(), 'left') plot.add_tools(PanTool(), WheelZoomTool(zoom_on_axis=False, speed=1 / 5000.)) doc = Document() doc.add_root(plot) if __name__ == "__main__": doc.validate() filename = "dateaxis.html"
#source= ColumnDataSource(data=source_users,source_finders) source = ColumnDataSource( data=dict(lat=lat_Miniboat_enthusiast, lon=lon_Miniboat_enthusiast, firstname=firstname_Miniboat_enthusiast, lastname=lastname_Miniboat_enthusiast, city=citys_Miniboat_enthusiast, state=states_Miniboat_enthusiast, phone=phone_Miniboat_enthusiast, email=email_Miniboat_enthusiast, institution=institution_Miniboat_enthusiast, country=country_Miniboat_enthusiast)) circle = Circle(x="lon", y="lat", size=6, fill_color="blue", fill_alpha=0.8, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), HoverTool(), ResetTool()) output_file("EP_people.html") hover = plot.select(dict(type=HoverTool)) hover.point_policy = "follow_mouse" hover.tooltips = OrderedDict([("Firstname", "@firstname"), ("Lastname", "@lastname"), ("City", "@city"), ("State", "@state"), ("Institution", "@institution"), ("Phone", "@phone"), ("Email", "@email")]) show(plot)
N = len(graph.vertices) node_indices = list(graph.vertices) plot = figure(title='Graph Layout Demonstration', x_range=(-1.1, 10.1), y_range=(-1.1, 10.1), tools='', toolbar_location=None) graph_renderer = GraphRenderer() graph_renderer.node_renderer.data_source.add(node_indices, 'index') graph_renderer.node_renderer.data_source.add( ['red', 'blue', 'green', 'orange'] * N, 'color') graph_renderer.node_renderer.glyph = Circle(radius=0.5, fill_color='color') start_indices = [] end_indices = [] for vertex in graph.vertices: for edge_end in graph.vertices[vertex]: start_indices.append(vertex) end_indices.append(edge_end) print(start_indices) print(end_indices) graph_renderer.edge_renderer.data_source.data = dict(start=start_indices, end=end_indices) # start of layout code
# nx.set_node_attributes(G,node_color, 'node_color') nx.set_node_attributes(G, node_size, 'node_size') # source=ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)},orient='index')) # mapper = LinearColorMapper(palette=pal_hex_lst, low=0, high=21) ### Initiate bokeh plot plot = figure(title="Resized Node Demo", x_range=(-1.1, 1.1), y_range=(-1.1, 1.1), tools="", toolbar_location=None) # Graph renderer using nx graph = from_networkx(G, nx.fruchterman_reingold_layout) # Style node # graph.node_renderer.data_source = source # graph.node_renderer.glyph = Circle(size='node_size', fill_color={'field': 'node_color', 'transform': mapper}) graph.node_renderer.glyph = Circle(size='node_size') graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1) plot.renderers.append(graph) show(plot) # plt.figure(figsize = (10,9)) # nx.draw_networkx(graph) # plt.show()
def Rips_Filtration(points, radius_range): source = ColumnDataSource(data=dict( x=points[:, 0], y=points[:, 1], sizes=radius_range[0] / 2 * np.ones(points.shape[0]), )) vline = ColumnDataSource( data=dict(s=[radius_range[0]], y=[0], angle=[np.pi / 2])) filt_plot = figure(title='Filtration', plot_width=300, plot_height=300, min_border=0, toolbar_location=None, match_aspect=True) glyph = Circle(x="x", y="y", radius="sizes", line_color="black", fill_color="green", fill_alpha=0.2, line_width=1) filt_plot.add_glyph(source, glyph) callback = CustomJS(args=dict(source=source, vline=vline), code=""" var data = source.data; var s = cb_obj.value var sizes = data['sizes'] for (var i = 0; i < sizes.length; i++) { sizes[i] = s/2 } var vdata = vline.data; var step = vdata['s'] step[0] = s vline.change.emit(); source.change.emit(); """) barcode_plot = figure(title='Barcode', plot_width=800, plot_height=200, min_border=0, toolbar_location=None, x_axis_label='Filtration Value', x_range=(radius_range[0], radius_range[1])) lscape_plot = figure(title='Landscapes', plot_width=800, plot_height=300, min_border=0, toolbar_location=None, x_axis_label='Filtration Value', x_range=(radius_range[0], radius_range[1])) barcode_plot.yaxis.major_tick_line_color = None # turn off y-axis major ticks barcode_plot.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks barcode_plot.yaxis.major_label_text_font_size = '0pt' # preferred method for removing tick labels rips = Rips(maxdim=1, thresh=radius_range[1], verbose=False) barcodes = rips.transform(points) H_0_Bars = barcodes[0] H_1_Bars = barcodes[1] H_0_color = '#1d07ad' H_1_color = '#009655' vertical_line_color = "#FB8072" for bar in range(len(H_0_Bars)): if H_0_Bars[bar, 1] < radius_range[1]: barcode_plot.line([H_0_Bars[bar, 0], H_0_Bars[bar, 1]], [bar / len(H_0_Bars), bar / len(H_0_Bars)], legend_label='H0 Bars', color=H_0_color, line_width=2) else: barcode_plot.line([H_0_Bars[bar, 0], radius_range[1]], [bar / len(H_0_Bars), bar / len(H_0_Bars)], legend_label='H0 Bars', color=H_0_color, line_width=2) for bar in range(len(H_1_Bars)): if H_1_Bars[bar, 1] < radius_range[1]: barcode_plot.line( [H_1_Bars[bar, 0], H_1_Bars[bar, 1]], [3 / 2 + bar / len(H_1_Bars), 3 / 2 + bar / len(H_1_Bars)], legend_label='H1 Bars', color=H_1_color, line_width=2) else: barcode_plot.line( [H_1_Bars[bar, 0], radius_range[1]], [3 / 2 + bar / len(H_1_Bars), 3 / 2 + bar / len(H_1_Bars)], legend_label='H1 Bars', color=H_1_color, line_width=2) barcode_plot.legend.location = "bottom_right" barcode_plot.ray(x="s", y="y", length="y", angle="angle", source=vline, color="#FB8072", line_width=2) H0rivet_barcode = ripser_to_rivet_bcode(H_0_Bars) L = compute_landscapes(H0rivet_barcode) for k in range(len(L.landscapes)): n = np.shape(L.landscapes[k].critical_points)[0] x = L.landscapes[k].critical_points[1:n, 0] y = L.landscapes[k].critical_points[1:n, 1] if k < 3: lscape_plot.line(x=x, y=y, color=H_0_color, line_alpha=1 / (k + 1), line_width=2, legend_label='H0: k =' + str(k + 2), muted_color=vertical_line_color, muted_alpha=1) else: lscape_plot.line(x=x, y=y, color=H_0_color, line_alpha=1 / (k + 1), line_width=2) H_1_rivet_barcode = ripser_to_rivet_bcode(H_1_Bars) L = compute_landscapes(H_1_rivet_barcode) for k in range(len(L.landscapes)): n = np.shape(L.landscapes[k].critical_points)[0] x = L.landscapes[k].critical_points[1:n, 0] y = L.landscapes[k].critical_points[1:n, 1] if k < 3: lscape_plot.line(x=x, y=y, color=H_1_color, line_alpha=1 / (k + 1), line_width=2, legend_label='H1: k =' + str(k + 1), muted_color=vertical_line_color, muted_alpha=1) else: lscape_plot.line(x=x, y=y, color=H_1_color, line_alpha=1 / (k + 1), line_width=2) lscape_plot.legend.location = "top_right" lscape_plot.legend.click_policy = "mute" lscape_plot.ray(x="s", y="y", length="y", angle="angle", source=vline, color=vertical_line_color, line_width=2) slider = Slider(start=radius_range[0], end=radius_range[1], value=radius_range[0], step=(radius_range[1] - radius_range[0]) / 100, title="Rips Parameter") slider.js_on_change('value', callback) layout = column(slider, filt_plot, barcode_plot, lscape_plot) return layout
for vertex in graph_data.vertexes: color_list.append(vertex.color) plot = figure(title='Graph Layout Demonstration', x_range=(0, WIDTH), y_range=(0, HEIGHT), tools='', plot_width=WIDTH, plot_height=HEIGHT, toolbar_location=None) graph = GraphRenderer() graph.node_renderer.data_source.add(node_indices, 'index') graph.node_renderer.data_source.add(color_list, 'color') graph.node_renderer.glyph = Circle(size=CIRCLE_SIZE, fill_color='color') # This is drawing the edges for start to end def get_edge_indexes(graph): start_indexes = [] end_indexes = [] for start_index, vertex in enumerate(graph_data.vertexes): for edge in vertex.edges: start_indexes.append(start_index) end_indexes.append(graph_data.vertexes.index(edge.destination)) return dict(start=start_indexes, end=end_indexes)
def generateNodeLinkGraph(file): #Reading the file file = file + '.csv' fname = os.path.join(server.config['UPLOAD_FOLDER'], file) f = open(fname, 'r') #Reading first line line1 = f.readline() names = line1[1:].split(';') # Rename duplicates since there are people with the same name seen = {} dupes = [] for index, name in enumerate(names): if name not in seen: seen[name] = 1 else: if seen[name] == 1: dupes.append((index, name)) seen[name] += 1 # add 1, 2 etc after the name for pair in dupes: index = pair[0] name = pair[1] for i in range(seen[name]): names[index] = name + str((i+1)) #print(names[index]) # Read csv df = pd.read_csv(f, names=names, sep=';') # Fix it df = df.reset_index(level=1) names.append("delete") df.columns = names del df["delete"] df.set_index([df.columns], inplace=True) # Get names again for later use names = df.columns.tolist() # Get 150*150 sub matrix since otherwise the plot is very slow.. df = df.head(150)[names[0:150]] names = df.columns.tolist() #Get total amount of nodes N = len(names) node_indices = list(range(N)) #Create list of numeric node indices # Scale for the repeating pattern of the colours scale = math.ceil(N / 256) #Iterate over dataframe and save non-zero edges start = [] #Contains starting node index of each edge end = [] #Contains ending node index of each edge tolerance = 0.75 #Determine which edges are shown and which are not index_count = 0 #Set start node index to 0 for row in df.itertuples(): #For each row in the dataframe index_count += 1 #Increase start node index by 1 element_count = 0 #(Re)set second node index to 0 for element in row: #For each element in each row element_count += 1 #Increase second node index by 1 if type(element) == float: #if element == 1.0: #Code in case for symmetric matrix, effectively halving running time of this loop # break #elif element > tolerance: if element > tolerance and not element == 1.0: start.append(index_count) #Add starting node index to the edge starting list end.append(element_count) #Add ending node index to the edge ending list #Create the plot with two axes, a title and interaction tools #plot = figure(title='Circular Node-Link Diagram', x_range=(0 - (N * 2.1) , N * 2.1), y_range=(0 - (N * 2.1) , N * 2.1), # tools='pan, wheel_zoom, reset', toolbar_location = 'right', frame_height = 400, frame_width = 400, output_backend="webgl") plot = Plot(x_range=Range1d(0 - (N * 2.1) , N * 2.1), y_range=Range1d(0 - (N * 2.1) , N * 2.1), toolbar_location = 'right', frame_height = 400, frame_width = 400, output_backend="webgl") plot.title.text = "Circular Node-Link Diagram" plot.add_tools(PanTool(), BoxZoomTool(), ResetTool()) #Create the graph object graph = GraphRenderer() #Assign the correct data for the edges #graph.edge_renderer.data_source.data = dict( # start = start, # end = end) #graph.edge_renderer.glyph = MultiLine(line_color = Viridis256[200]) #Assign the correct data for the nodes graph.node_renderer.data_source.add(node_indices, 'index') graph.node_renderer.data_source.add(Viridis256 * scale, 'color') graph.node_renderer.glyph = Circle(radius = N * 0.0025, fill_color='color') #Start of circular layout code circ = [i * 2 * math.pi/N for i in node_indices] x = [2 * N * math.cos(i) for i in circ] y = [2 * N * math.sin(i) for i in circ] #Assign the correct x and y values to all nodes graph_layout = dict(zip(node_indices, zip(x, y))) graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) #Arrow code test for start_index in start: start_index -= 1 for end_index in end: end_index -= 1 plot.add_layout(Arrow(end = NormalHead(fill_color = Viridis256[200], size = N * 0.1), x_start = x[start_index], y_start = y[start_index], x_end = x[end_index], y_end = y[end_index], line_color = Viridis256[200])) end_index += 1 start_index += 1 #Show the plot plot.renderers.append(graph) script, div = components(plot) return script, div
def bkplot(self, x, y, color='None', radii='None', ps=20, minps=0, alpha=0.8, pw=600, ph=400, palette='Inferno256', style='smapstyle', Hover=True, title='', table=False, table_width=600, table_height=150, add_colorbar=True, Periodic_color=False, return_datasrc=False, frac_load=1.0, marker=['circle'], seed=0, **kwargs): from bokeh.layouts import row, widgetbox, column, Spacer from bokeh.models import HoverTool, TapTool, FixedTicker, Circle, WheelZoomTool from bokeh.models import CustomJS, Slider, Rect, ColorBar, HoverTool, LinearColorMapper, BasicTicker from bokeh.plotting import figure import bokeh.models.markers as Bokeh_markers from bokeh.models import ColumnDataSource, CDSView, IndexFilter from bokeh.palettes import all_palettes, Spectral6, Inferno256, Viridis256, Greys256, Magma256, Plasma256 from bokeh.palettes import Spectral, Inferno, Viridis, Greys, Magma, Plasma from bokeh.models import LogColorMapper, LogTicker, ColorBar, BasicTicker, LinearColorMapper from bokeh.models.widgets import DataTable, TableColumn, NumberFormatter, Div import pandas as pd # if (title==''): title=self.name fulldata = self.pd idx = np.arange(len(fulldata)) fulldata['id'] = idx nload = int(frac_load * len(fulldata)) np.random.seed(seed) np.random.shuffle(idx) idload = np.sort(idx[0:nload]) data = self.pd.iloc[idload].copy() if palette == 'cosmo': COLORS = cosmo() else: COLORS = locals()[palette] marklist = [ 'circle', 'diamond', 'triangle', 'square', 'asterisk', 'cross', 'inverted_triangle' ] if not marker[0] in marklist: marker = marklist # TOOLS="resize,crosshair,pan,wheel_zoom,reset,tap,save,box_select,box_zoom,lasso_select" TOOLS = "pan,reset,tap,save,box_zoom,lasso_select" wheel_zoom = WheelZoomTool(dimensions='both') if Hover: proplist = [] for prop in data.columns: if prop not in [ "CV1", "CV2", "Cv1", "Cv2", "cv1", "cv2", "colors", "radii", "id" ]: proplist.append((prop, '@' + prop)) hover = HoverTool(names=["mycircle"], tooltips=[("id", '@id')]) for prop in proplist: hover.tooltips.append(prop) plot = figure(title=title, plot_width=pw, active_scroll=wheel_zoom, plot_height=ph, tools=[TOOLS, hover, wheel_zoom], **kwargs) else: plot = figure(title=title, plot_width=pw, active_scroll=wheel_zoom, plot_height=ph, tools=[TOOLS], **kwargs) # selection glyphs and plot styles mdict = { 'circle': 'Circle', 'diamond': 'Diamond', 'triangle': 'Triangle', 'square': 'Square', 'asterisk': 'Asterisk', 'cross': 'Cross', 'inverted_triangle': 'InvertedTriangle' } initial_circle = Circle(x='x', y='y') selected_circle = getattr(Bokeh_markers, mdict[marker[0]])(fill_alpha=0.7, fill_color="blue", size=ps * 1.5, line_color="blue") nonselected_circle = getattr(Bokeh_markers, mdict[marker[0]])(fill_alpha=alpha * 0.5, fill_color='colors', line_color='colors', line_alpha=alpha * 0.5) # set up variable point size if radii == 'None': r = [ps for i in range(len(data))] data['radii'] = r else: if data[radii].dtype == 'object': # Categorical variable for radii grouped = data.groupby(radii) i = 0 r = np.zeros(len(data)) for group_item in grouped.groups.keys(): r[grouped.groups[group_item].tolist()] = i**2 i = i + 2 else: r = [val for val in data[radii]] rn = self.normalize(r) rad = [minps + ps * np.sqrt(val) for val in rn] data['radii'] = rad # setup variable point color if color == 'None': c = ["#31AADE" for i in range(len(data))] data['colors'] = c datasrc = ColumnDataSource(data) getattr(plot, marker[0])(x, y, source=datasrc, size='radii', fill_color='colors', fill_alpha=alpha, line_color='colors', line_alpha=alpha, name="mycircle") renderer = plot.select(name="mycircle") renderer.selection_glyph = selected_circle renderer.nonselection_glyph = nonselected_circle else: if data[color].dtype == 'object': # Categorical variable for colors grouped = data.groupby(color) # COLORS=Spectral[len(grouped)] i = 0 nc = len(COLORS) istep = int(nc / len(grouped)) cat_colors = [] for group_item in grouped.groups.keys(): # data.loc[grouped.groups[group_item],'colors']=COLORS[i] # print(group_item,COLORS[i]) i = min(i + istep, nc - 1) cat_colors.append(COLORS[i]) #colors=[ '#d53e4f', '#3288bd','#fee08b', '#99d594'] datasrc = ColumnDataSource(data) view = [] # used_markers=[] # marker=['circle','diamond','triangle','square','asterisk','cross','inverted_triangle'] #while True: # for x in marker: # used_markers.append(x) # if len(used_markers)>len(grouped): break i = 0 #print used_markers for group_item in grouped.groups.keys(): view.append( CDSView( source=datasrc, filters=[IndexFilter(grouped.groups[group_item])])) cname = 'mycircle' + str(i) #print used_markers[i] try: mk = marker[i] except: mk = marker[0] getattr(plot, mk)(x, y, source=datasrc, size='radii', fill_color=cat_colors[i], muted_color=cat_colors[i], muted_alpha=0.2, fill_alpha=alpha, line_alpha=alpha, line_color=cat_colors[i], name=cname, legend=group_item, view=view[i]) selected_mk = getattr(Bokeh_markers, mdict[mk])(fill_alpha=0.7, fill_color="blue", size=ps * 1.5, line_color="blue", line_alpha=0.7) nonselected_mk = getattr(Bokeh_markers, mdict[mk])( fill_alpha=alpha * 0.5, fill_color=cat_colors[i], line_color=cat_colors[i], line_alpha=alpha * 0.5) renderer = plot.select(name=cname) renderer.selection_glyph = selected_mk renderer.nonselection_glyph = nonselected_mk i += 1 plot.legend.location = "top_left" plot.legend.orientation = "vertical" plot.legend.click_policy = "hide" else: if Periodic_color: # if periodic property then generate periodic color palatte blendcolor = interpolate(COLORS[-1], COLORS[0], len(COLORS) / 5) COLORS = COLORS + blendcolor groups = pd.cut(data[color].values, len(COLORS)) c = [COLORS[xx] for xx in groups.codes] data['colors'] = c datasrc = ColumnDataSource(data) getattr(plot, marker[0])(x, y, source=datasrc, size='radii', fill_color='colors', fill_alpha=alpha, line_color='colors', line_alpha=alpha, name="mycircle") renderer = plot.select(name="mycircle") renderer.selection_glyph = selected_circle renderer.nonselection_glyph = nonselected_circle color_mapper = LinearColorMapper(COLORS, low=data[color].min(), high=data[color].max()) colorbar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(), label_standoff=4, border_line_color=None, location=(0, 0), orientation="vertical") colorbar.background_fill_alpha = 0 colorbar.border_line_alpha = 0 if add_colorbar: plot.add_layout(colorbar, 'left') # Overview plot oplot = figure(title='', plot_width=200, plot_height=200, toolbar_location=None) oplot.circle(x, y, source=datasrc, size=4, fill_alpha=0.6, line_color=None, name="mycircle") orenderer = oplot.select(name="mycircle") orenderer.selection_glyph = selected_circle # orenderer.nonselection_glyph = nonselected_circle rectsource = ColumnDataSource({'xs': [], 'ys': [], 'wd': [], 'ht': []}) jscode = """ var data = source.data; var start = range.start; var end = range.end; data['%s'] = [start + (end - start) / 2]; data['%s'] = [end - start]; source.change.emit(); """ plot.x_range.callback = CustomJS(args=dict(source=rectsource, range=plot.x_range), code=jscode % ('xs', 'wd')) plot.y_range.callback = CustomJS(args=dict(source=rectsource, range=plot.y_range), code=jscode % ('ys', 'ht')) rect = Rect(x='xs', y='ys', width='wd', height='ht', fill_alpha=0.1, line_color='black', fill_color='red') oplot.add_glyph(rectsource, rect) # plot style plot.toolbar.logo = None oplot.toolbar.logo = None if style == 'smapstyle': plist = [plot, oplot] else: plist = [oplot] for p in plist: p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.xaxis[0].ticker = FixedTicker(ticks=[]) p.yaxis[0].ticker = FixedTicker(ticks=[]) p.outline_line_width = 0 p.outline_line_alpha = 0 p.background_fill_alpha = 0 p.border_fill_alpha = 0 p.xaxis.axis_line_width = 0 p.xaxis.axis_line_color = "white" p.yaxis.axis_line_width = 0 p.yaxis.axis_line_color = "white" p.yaxis.axis_line_alpha = 0 # table if table: tcolumns = [ TableColumn(field='id', title='id', formatter=NumberFormatter(format='0')) ] for prop in data.columns: if prop not in [ "CV1", "CV2", "Cv1", "Cv2", "cv1", "cv2", "colors", 'id', "radii" ]: if data[prop].dtype == 'object': tcolumns.append(TableColumn(field=prop, title=prop)) if data[prop].dtype == 'float64': tcolumns.append( TableColumn( field=prop, title=prop, formatter=NumberFormatter(format='0.00'))) if data[prop].dtype == 'int64': tcolumns.append( TableColumn(field=prop, title=prop, formatter=NumberFormatter(format='0'))) data_table = DataTable(source=datasrc, fit_columns=True, scroll_to_selection=True, columns=tcolumns, name="Property Table", width=table_width, height=table_height) div = Div(text="""<h6><b> Property Table </b> </h6> <br>""", width=600, height=10) if return_datasrc: return plot, oplot, column(widgetbox(div), Spacer(height=10), widgetbox(data_table)), datasrc else: return plot, oplot, column(widgetbox(div), Spacer(height=10), widgetbox(data_table)) else: return plot, oplot
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes from bokeh.palettes import Spectral4 G = nx.karate_club_graph() 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 = "Graph Interaction Demonstration" 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.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2]) graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1]) graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5) graph_renderer.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=5) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = EdgesAndLinkedNodes()
plot = Plot(plot_width=1600, plot_height=1000, x_range=Range1d(-2, 1002), y_range=Range1d(-5, 5)) plot.title.text = "Graph Interaction Demonstration" node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("p", "@p")]) plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool()) graph_layout = style() edge_attrs = {} graph_renderer = from_networkx(G, graph_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=15, fill_color="colors", line_width=1.0) graph_renderer.node_renderer.data_source.data["colors"] = ["red" ] * len(nodeCells) graph_renderer.edge_renderer.glyph = MultiLine(line_color="colors", line_alpha=0.8, line_width="widths") graph_renderer.edge_renderer.data_source.data["colors"] = ["purple"] * ( len(nodeCells) - 1) graph_renderer.edge_renderer.data_source.data["widths"] = [2] * ( len(nodeCells) - 1) plot.renderers.append(graph_renderer) slider = createTimeSlider() curdoc().add_root(column(slider, plot))
ydr = Range1d(start=-1.25, end=1.25) plot = Plot(x_range=xdr, y_range=ydr, width=600, height=600) plot.toolbar_location = None plot.outline_line_color = None start_angle = pi + pi / 4 end_angle = -pi / 4 max_kmh = 250 max_mph = max_kmh * 0.621371 major_step, minor_step = 25, 5 plot.add_glyph( Circle(x=0, y=0, radius=1.00, fill_color="white", line_color="black")) plot.add_glyph( Circle(x=0, y=0, radius=0.05, fill_color="gray", line_color="black")) plot.add_glyph( Text(x=0, y=+0.15, text=["km/h"], text_color="red", text_align="center", text_baseline="bottom", text_font_style="bold")) plot.add_glyph( Text(x=0, y=-0.15, text=["mph"],
plot.add_layout(xgrid) yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0) yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10) plot.add_layout(yaxis, "right") filters = [ IndexFilter( list( sprint.query( 'Medal == "gold" and Year in [1988, 1968, 1936, 1896]').index)) ] medal = Circle(x="MetersBack", y="Year", size=10, fill_color="MedalFill", line_color="MedalLine", fill_alpha=0.5) medal_renderer = plot.add_glyph(source, medal) #sprint[sprint.Medal=="gold" * sprint.Year in [1988, 1968, 1936, 1896]] plot.add_glyph(source, Text(x="MetersBack", y="Year", x_offset=10, text="Name"), view=CDSView(source=source, filters=filters)) plot.add_glyph( source, Text(x=7.5, y=1942, text=["No Olympics in 1940 or 1944"], text_font_style="italic",
def create(self): manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = GlyphRenderer(data_source=self.source, glyph=cty_glyph) hwy = GlyphRenderer(data_source=self.source, glyph=hwy_glyph) tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(plot=plot, renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(plot=plot, renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(plot=plot, renderers=[cty, hwy], dimensions=['width']) plot.tools.extend([cty_hover_tool, hwy_hover_tool, select_tool]) plot.renderers.extend([cty, hwy, ygrid]) controls = VBox(children=[ manufacturer_select, model_select, transmission_select, drive_select, class_select ], width=200) top_panel = HBox(children=[controls, plot]) layout = VBox(children=[top_panel, data_table]) return layout
def create_plot(inputdata, xcol='cv1', ycol='cv2', zcol='energy'): # xval=copy(data[:,xcol]) # yval=copy(data[:,ycol]) # cval=copy(data[:,ccol]) # colors=cosmo_colors(cval) # datasrc = ColumnDataSource( # data=dict( # x=xval, # y=yval, # colors=colors, # ) # ) # datasrc = copy(inputdata) print "Hello", datasrc source = ColumnDataSource({'xs': [], 'ys': [], 'wd': [], 'ht': []}) jscode = """ var data = source.get('data'); var start = range.get('start'); var end = range.get('end'); data['%s'] = [start + (end - start) / 2]; data['%s'] = [end - start]; source.trigger('change'); """ initial_circle = Circle(x='x', y='y') selected_circle = Circle(fill_alpha=1, fill_color="firebrick", size=20) nonselected_circle = Circle(fill_alpha=0.4, fill_color='colors', line_color=None) title = " " TOOLS = "crosshair,pan,wheel_zoom,box_zoom,reset,box_select,lasso_select,tap,save" #TOOLS="pan,wheel_zoom,box_select,lasso_select,reset" # The main Plot of tab 1 p1 = figure(title=title, tools=TOOLS, height=800, width=800, toolbar_location="above") colors = cosmo_colors(datasrc.data['energy']) p1.circle('cv1', 'cv2', source=datasrc, size=5, fill_color='blue', fill_alpha=0.8, line_color=None, name="mycircle") p1.x_range.callback = CustomJS(args=dict(source=source, range=p1.x_range), code=jscode % ('xs', 'wd')) p1.y_range.callback = CustomJS(args=dict(source=source, range=p1.y_range), code=jscode % ('ys', 'ht')) renderer = p1.select(name="mycircle") renderer.selection_glyph = selected_circle renderer.nonselection_glyph = nonselected_circle p1.xgrid.grid_line_color = None p1.ygrid.grid_line_color = None p1.xaxis[0].ticker = FixedTicker(ticks=[]) p1.yaxis[0].ticker = FixedTicker(ticks=[]) p1.outline_line_width = 0 p1.outline_line_color = "white" p1.xaxis.axis_line_width = 0 p1.xaxis.axis_line_color = "white" p1.yaxis.axis_line_width = 0 p1.yaxis.axis_line_color = "white" # The overview plot p2 = figure(tools='', height=300, width=300) p2.xgrid.grid_line_color = None p2.ygrid.grid_line_color = None p2.xaxis[0].ticker = FixedTicker(ticks=[]) p2.yaxis[0].ticker = FixedTicker(ticks=[]) p2.circle(x='cv1', y='cv2', source=datasrc, size=5, fill_color=colors, fill_alpha=0.8, line_color=None, name='mycircle') renderer = p2.select(name="mycircle") renderer.selection_glyph = selected_circle renderer.nonselection_glyph = nonselected_circle p2.outline_line_width = 0 p2.outline_line_alpha = 0.3 p2.outline_line_color = "white" p2.xaxis.axis_line_width = 0 p2.xaxis.axis_line_color = "white" p2.yaxis.axis_line_width = 0 p2.yaxis.axis_line_color = "white" rect = Rect(x='xs', y='ys', width='wd', height='ht', fill_alpha=0.1, line_color='black', fill_color='black') p2.add_glyph(source, rect) callback = CustomJS(code=""" var inds = cb_obj.get('selected')['1d'].indices[0]; var str = "" + inds; var pad = "0000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "connect 1.0 1.2 (carbon) (hydrogen) SINGLE CREATE ; connect 1.0 1.2 (nitrogen) (hydrogen) SINGLE CREATE ; connect 1.0 4.2 (carbon) (nitrogen) SINGLE CREATE ; connect 3.0 5 (phosphorus) (iodine) SINGLE CREATE ; set perspectiveDepth OFF " var file= "javascript:Jmol.script(jmolApplet0," + "'load plot-server/static/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; """) taptool = p1.select(type=TapTool) taptool.callback = callback slider_callback = CustomJS(code=""" var inds = cb_obj.value; var str = "" + inds; var pad = "0000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "connect 1.0 1.2 (carbon) (hydrogen) SINGLE CREATE ; connect 1.0 1.2 (nitrogen) (hydrogen) SINGLE CREATE ; connect 1.0 4.2 (carbon) (nitrogen) SINGLE CREATE ; connect 3.0 5 (phosphorus) (iodine) SINGLE CREATE ; set perspectiveDepth OFF " var file= "javascript:Jmol.script(jmolApplet0," + "'load plot-server/static/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; """) slider = Slider( start=0, end=2600, value=0, step=1, title="selected") #,callback=CustomJS.from_py_func(slider_callback2)) slider.js_on_change('value', slider_callback) return p1, p2, slider
data_df = load_csv('./embedding_visualization/data/show.csv') features_list = [ i for i in list(data_df.columns) if i not in ['tsne_x', 'tsne_y'] ] source = ColumnDataSource(data_df) cls_color_mapper, color_cls_list, _ = get_color_mapper(features_list[0]) p = figure(plot_width=800, plot_height=800, match_aspect=True, tools=['pan', 'box_zoom', 'reset'], title='', sizing_mode='scale_height', output_backend="webgl") cr = p.circle(x='tsne_x', y='tsne_y', color=cls_color_mapper, source=source) cr.selection_glyph = Circle(fill_color=cls_color_mapper, line_color=cls_color_mapper) cr.nonselection_glyph = Circle(fill_color=cls_color_mapper, line_color=cls_color_mapper, fill_alpha=0.05, line_alpha=0.05) color_bar = ColorBar(color_mapper=LinearColorMapper(palette="Viridis256", low=1, high=10), label_standoff=12, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') color_bar.visible = False if type(cls_color_mapper['transform']) is LinearColorMapper: color_bar.color_mapper = cls_color_mapper['transform'] # p.add_layout(color_bar, 'right')
def plot_net(df,G): colors=['red','yellow','green'] central=networkx.in_degree_centrality(G) Ss=np.array(central.values()) Ss=((Ss-min(Ss)+0.00001)/(max(Ss)-min(Ss)+0.00001)*0.045+0.005)*2/(len(G.nodes())**0.25) Sizes=dict(zip(central.keys(),Ss)) pts = networkx.spring_layout(G) mi, ma=np.array(pts.values()).min()-0.1, np.array(pts.values()).max()+0.1 def add_arrow(x1,x2,r=0.2): return [x2-(x2-x1)*r,x2] def change_nrev(nrev): if nrev<=1: return str(int(nrev))+' review' else: return str(int(nrev))+' reviews' nodes=sorted(G.nodes()) df_s=df.sort('ASIN') source = ColumnDataSource( data=dict( x=[pts[node][0] for node in nodes], y=[pts[node][1] for node in nodes], ASIN=df_s.ASIN.tolist(), col=[colors[networkx.shortest_path_length(G,df.ASIN[0],node)] for node in nodes], siz=[Sizes[node] for node in nodes], rev=map(lambda r:'| '.join(map(str,r)),df_s.Review), img=df_s.IMG.tolist(), rating=map(lambda x: "{:.1f}".format(x) ,df_s['Average rating'].tolist()), nrev=map(change_nrev,df_s['Number of reviews'].tolist()), nrev_num=df_s['Number of reviews'].tolist(), rating_num=df_s['Average rating'].tolist(), name=df_s.Name, rd=[Sizes[node]*500 for node in nodes], outrd=[Sizes[node]*600 for node in nodes] ) ) mostrat=df[df['Average rating']==df['Average rating'].max()]['ASIN'].tolist() mostrev=df[df['Number of reviews']==df['Number of reviews'].max()]['ASIN'].tolist() TOOLS = 'pan,box_zoom,lasso_select,reset,,wheel_zoom,resize,help' p = figure( x_range = (mi,ma), y_range = (mi,ma), height= 600, width= 600, title="Network of related products", tools=TOOLS ) for edge in G.edges(): p.line( x= [pts[pt][0] for pt in edge], y= [pts[pt][1] for pt in edge], line_cap='round', line_color='blue', ) p.line( x= add_arrow(*[pts[pt][0] for pt in edge]), y= add_arrow(*[pts[pt][1] for pt in edge]), line_cap='square', line_color='blue', line_width=5, line_alpha=0.5 ) circle=Circle(x='x',y='y',radius='siz',fill_color='col',fill_alpha=0.8,line_alpha=0.5) circle_renderer=p.add_glyph(source,circle) hover = HoverTool(tooltips=""" <div> <div> <img src="@img" height="60" alt="@img" width="60" style="float: left; margin: 0px 15px 15px 0px;" border="2" ></img> </div> <div style="width:250px"> <span style="font-size: 12px; font-weight: bold;">@name (@ASIN)</span> <br /> <span style="font-size:11.5px;"> Rating: @rating (@nrev) </span> <br /> <span style="font-size: 11px; color: #966 ; width:150px;">@rev</span> </div> </div> """,renderers=[circle_renderer]) p.add_tools(hover) url = 'http://www.amazon.com/o/ASIN/@ASIN' taptool = TapTool(action=OpenURL(url=url),renderers=[circle_renderer]) # taptool has differnet attr name due to different version of bokeh. # taptool = TapTool(callback=OpenURL(url=url),renderers=[circle_renderer]) p.tools.append(taptool) p.annulus( x=[pts[node][0] for node in mostrat], y=[pts[node][1] for node in mostrat], inner_radius=[Sizes[node] for node in mostrat], outer_radius=[Sizes[node]*1.5 for node in mostrat], color='orange',alpha=0.8) p.annulus( x=[pts[node][0] for node in mostrev], y=[pts[node][1] for node in mostrev], inner_radius=[Sizes[node] for node in mostrev], outer_radius=[Sizes[node]*1.5 for node in mostrev], color='purple',alpha=0.8) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.xaxis.major_label_text_color = None p.yaxis.major_label_text_color = None scatter=figure( x_range = (-df['Number of reviews'].max()*0.1,df['Number of reviews'].max()*1.1), y_range = (-0.5,5.5), height= 600, width= 500, title="Average rating and number of reviews", tools=TOOLS+",crosshair" ) scatter.circle(x='nrev_num',y='rating_num',radius="rd",color='col',alpha=0.8,source=source) scatter.annulus(x='nrev_num',y='rating_num',inner_radius="rd",outer_radius='outrd',color='black',alpha=0.8,source=source) scatter.xaxis.axis_label = "Number of reviews" scatter.yaxis.axis_label = "Average rating" return gridplot([[p,scatter]])
from bokeh.io import output_file, show from bokeh.models import Circle from bokeh.plotting import figure output_file("styling_selections.html") plot = figure(width=400, height=400, tools="tap", title="Select a circle") renderer = plot.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=50) selected_circle = Circle(fill_alpha=1, fill_color="firebrick", line_color=None) nonselected_circle = Circle(fill_alpha=0.2, fill_color="blue", line_color="firebrick") renderer.selection_glyph = selected_circle renderer.nonselection_glyph = nonselected_circle show(plot)
map_options = GMapOptions(lat=37.76487, lng=-122.41948, zoom=8, map_type="roadmap") plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title=None, toolbar_location=None, min_border=0, ) circle = Circle(y="longitude", x="latitude", size=10, fill_color="red", line_color=None) plot.add_glyph(ColumnDataSource(stations), circle) plot.add_tools(PanTool(), WheelZoomTool()) with open('d3_geo.html', 'r') as f: d3_geo = Template(f.read()) html = file_html(plot, CDN, "Map", template=d3_geo) with open('bokeh_google_station_map.html', 'w') as f: f.write(html)
def create_graph(): #Find the layout and color choice if radio_layout.active == 0: lay = 'WDegreepos' elif radio_layout.active == 1: lay = 'bwcentralpos' else: lay = 'ccentralpos' if radio_color.active == 0: col = 'DegCol' elif radio_color.active == 1: col = 'Colbw' elif radio_color.active == 2: col = 'friend' elif radio_color.active == 3: col = 'reviewcount' else: col = 'comprank' # Create Network view graph = GraphRenderer() graph.node_renderer.data_source.data = nodes_df(G, col) graph.edge_renderer.data_source.data = edges_df(G) graph.node_renderer.glyph = Circle(size='size', fill_color='Col', line_color="black", line_alpha=0.1, fill_alpha=1) graph.edge_renderer.glyph = MultiLine(line_alpha='alpha', line_width=0.1, line_color="#A0DF3F") graph_layout = dict(nx.get_node_attributes(G, lay)) graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) # Glyph properties on selection graph.selection_policy = NodesAndLinkedEdges() graph.inspection_policy = EdgesAndLinkedNodes() graph.node_renderer.selection_glyph = Circle(size=12, fill_color='#0A5EB6', line_color="#002217") graph.edge_renderer.selection_glyph = MultiLine(line_color="#2972BE", line_width=0.5, line_alpha=0.4) # Adding graph to plot plot = figure(title="Yelp Users Layout", x_range=(-6.5, 6.5), y_range=(-6.5, 6.5), plot_width=525, plot_height=525, toolbar_location="above") plot.outline_line_alpha = 0 plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.xaxis.visible = False plot.yaxis.visible = False plot.renderers.append(graph) plot.add_tools(TapTool()) return plot
x=[galaxy['ra'].value - 2.], y=[galaxy['dec'].value + 2], w=4, h=4, global_alpha=0.95) p2.circle(qso['RA'][0, :], qso['DEC'][0, :], fill_color='#FFCC66', size=8) qso_syms = p2.circle('ra_qso', 'dec_qso', source=qso_catalog, fill_color='#FFCC66', size=8, name="qso_points_to_hover") qso_syms.selection_glyph = Circle(fill_alpha=1.0, fill_color="gold", radius=1.5, line_color='purple', line_width=3) qso_syms.nonselection_glyph = Circle(fill_alpha=0.2, fill_color="blue", line_color="firebrick") hist_plot = figure(plot_height=600, plot_width=250, outline_line_color='black', \ x_range=[-0.1,2.2], y_range=[0,300], toolbar_location=None, x_axis_type = None, title='Time Required in Hours') hist_plot.quad(top='cos', source=hist_source, bottom=0., left=0, right=1, color='coscolor',
FRIEND_COLOR, NOT_FRIEND_COLOR = "red", "black" edge_attrs = {} for start_node, end_node, _ in G.edges(data=True): edge_color = FRIEND_COLOR if G.nodes[start_node] == G.nodes[end_node][ "test"] else NOT_FRIEND_COLOR edge_attrs[(start_node, end_node)] = edge_color nx.set_edge_attributes(G, edge_attrs, "edge_color") # Show with Bokeh 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 = "Graph Interaction Demonstration" node_hover_tools = [] for col in cols: node_hover_tool = HoverTool( tooltips=[('Name', col[0]), ("index", "@index"), (col[0], "@club")]) plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1) plot.renderers.append(graph_renderer) output_file("interactive_graphs.html") show(plot)
height=600, min_border=0, toolbar_location=None, background_fill_color='#F0F0F0', border_fill_color='lightgray', ) line_glyph = Line(x="x", y="y", line_color="navy", line_width=2, line_dash="dashed") line = plot.add_glyph(source, line_glyph) circle = Circle(x="x", y="y2", size=6, line_color="red", fill_color="orange", fill_alpha=0.6) circle = plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() preview_save = SaveTool() plot.add_tools(pan, wheel_zoom, preview_save) # Add axes (Note it's important to add these before adding legends in side panels) plot.add_layout(LinearAxis(), 'below') plot.add_layout(LinearAxis(), 'left') plot.add_layout(LinearAxis(), 'right')
def draw(self): graph = self.graph N = len(graph.vertices) node_indices = list(graph.vertices.keys()) plot = figure(title="Graph Layout Demonstration", x_range=(-6, 6), y_range=(-6, 6), tools="", toolbar_location=None) graph_render = GraphRenderer() graph_render.node_renderer.data_source.add(node_indices, 'index') node_colors = [] for vert in graph.vertices: node_colors.append(graph.vertices[vert].color) # node_colors = ['red'] * int(N / 2) # another_color = ['blue'] * int(N/2) # node_colors.extend(another_color) # if N % 2 != 0: # node_colors.extend(['green']) graph_render.node_renderer.data_source.add(node_colors, 'color') graph_render.node_renderer.glyph = Circle(radius=0.25, fill_color="color") edge_start = [] edge_end = [] for vert_id in node_indices: for v in graph.vertices[vert_id].edges: edge_start.append(vert_id) edge_end.append(v) graph_render.edge_renderer.data_source.data = dict(start=edge_start, end=edge_end) ### start of layout code # circ = [i*2*math.pi/8 for i in node_indices] # x = [math.cos(i) for i in circ] # y = [math.sin(i) for i in circ] x = [] y = [] for vert_id in node_indices: vertex = graph.vertices[vert_id] x.append(vertex.x) y.append(vertex.y) graph_layout = dict(zip(node_indices, zip(x, y))) graph_render.layout_provider = StaticLayoutProvider( graph_layout=graph_layout) plot.renderers.append(graph_render) labelSource = ColumnDataSource( data=dict(x=x, y=y, names=[vert_id for vert_id in graph.vertices])) labels = LabelSet(x='x', y='y', text='names', level='glyph', text_align='center', text_baseline='middle', source=labelSource, render_mode='canvas') plot.add_layout(labels) output_file("graph_demo.html") # output_file("graph.html") show(plot) # graph = Graph() # Instantiate your graph # graph.add_vertex('0') # graph.add_vertex('1') # graph.add_vertex('2') # graph.add_vertex('3') # graph.add_vertex('4') # graph.add_edge('0', '1') # graph.add_edge('0', '3') # graph.add_edge('3', '4') # bg = BokehGraph(graph) # bg.draw()
xdr = DataRange1d(sources=[source.columns("index")]) ydr = DataRange1d(sources=[source.columns("cty"), source.columns("hwy")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=1000, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = GlyphRenderer(data_source=source, glyph=cty_glyph) hwy = GlyphRenderer(data_source=source, glyph=hwy_glyph) tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"),
fig.add_tools(HoverTool(renderers=[dc], show_arrow=False, line_policy='next', tooltips=hover_dcline)) selected_line = MultiLine(line_color="color", line_alpha="line_alpha", line_width=4) l.selection_glyph = selected_line l.nonselection_glyph = selected_line l.data_source.selected.on_change('multiline_indices', update_lodf_color) ## nodes plot color = palettes.Category20b[4] # color sample for various states normal-hover-selected-notselected n = fig.circle("x", "y", size=4, fill_alpha=0.8, fill_color=color[3], source=source_nodes) fig.add_tools(HoverTool(renderers=[n], tooltips=hover_node)) # define color when (not-) selected selected_node = Circle(fill_alpha=0.8, fill_color=color[0], line_color=None) nonselected_node = Circle(fill_alpha=0.6, fill_color=color[3], line_color=None) # and trigger it correctly n.selection_glyph = selected_node n.nonselection_glyph = nonselected_node #dir(n.data_source.selected) #n.data_source.on_change('selected', update_stacked_bars) n.data_source.selected.on_change('indices', update_stacked_bars) #inidcator for data-load source_ind = ColumnDataSource(data=dict(x=[1], y=[1], color=["green"])) fig_indicator = figure(x_range=(0, 8), y_range=(0, 2), toolbar_location=None, tools="", plot_height=50, plot_width=300) label = Label(x=1.8, y=.8, text="Data is Loaded!", text_alpha=1) fig_indicator.add_layout(label)
G.add_nodes_from(range(8), name=class_names) G.add_edges_from(needed_edges) plot = Plot(aspect_ratio=1 / 1, sizing_mode='scale_both', margin=(10, 5, 5, 20), x_range=Range1d(-1.3, 2.7), y_range=Range1d(-1.6, 1.2)) plot.title.text = "Class Populations for Infectious Disease Outbreak" plot.title.text_font_size = '14pt' graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0)) #creating the nodes/circles for the network graph graph_renderer.node_renderer.data_source.add(Colorblind8, 'color') graph_renderer.node_renderer.data_source.add(practice_sizes, 'size') graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='color') graph_renderer.node_renderer.data_source.data['name'] = [ 'Susceptible', 'Exposed', 'Unknown Asymptomatic Infected', 'Known Asymptomatic Infected', 'Non-Hospitalized Symptomatic Infected', 'Hospitalized Symptomatic Infected', 'Recovered', 'Dead' ] graph_renderer.node_renderer.selection_glyph = Circle(size=30, fill_color=Spectral4[2]) graph_renderer.node_renderer.hover_glyph = Circle(size=30, fill_color=Spectral4[1]) graph_renderer.node_renderer.data_source #Creating the edges for the network graph graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=6)