def googleMaps(dataset): ownAPIKey= 'go_get_it_from_google_maps_api' gmaps.configure(api_key=ownAPIKey) # create the info box template info_box_template = """ <dl> <dt>Name</dt><dd>{name}</dd> <dt>ID</dt><dd>{id}</dd> <dt>Score</dt><dd>{score}</dd> <dt>Location</dt><dd>{location}</dd> <dt>Availability (%)</dt><dd>{available}</dd> <dt>URL</dt><dd>{listing_url}</dd> </dl> """ dataset.drop(columns=['description'], inplace=True) # drop description as it is too long gmap_dict= dataset.to_dict('records') # convert each row into a dictionary of the list gmap_locations =dataset['location'].to_list() # to show the markers on the map gmap_info = [info_box_template.format(**id) for id in gmap_dict] #map the gmap_dict with the info box template marker_layer = gmaps.marker_layer(gmap_locations, info_box_content=gmap_info) # create the markers to be shown on google map fig = gmaps.figure() fig.add_layer(marker_layer) # combine with the current map embed_minimal_html('map.html', views=[fig])
def PlotMap(): # Fucntion to create basemap global count global community gmaps.configure('AIzaSyBwEyjaABv6E1VJK3P_GKmMrvCIs8QEBJI') # ============================================================================= # m = Basemap(projection='mill',llcrnrlon=min(count['lon']),llcrnrlat=min(count['lat']),urcrnrlat=max(count['lat']),urcrnrlon=max(count['lon'])) # m.drawstates() # m.drawcoastlines() # m.drawcounties() # ============================================================================= #Plotting the data # ============================================================================= # lon=np.array(count['lon']) # lat=np.array(count['lat']) # data=np.array(count['english']) # x,y = m(lon,lat) # m.scatter(x,y,data) # ============================================================================= # ============================================================================= # data = [(float(count.iloc[i]['lat']), float(count.iloc[i]['lon'])) for i in range(len(count))] # print(data) # gmaps.heatmap(data) # ============================================================================= locations = count[['lat', 'lon']] weight = count['english'] fig = gmaps.figure() fig.add_layer(gmaps.heatmap_layer(locations, weights=weight)) embed_minimal_html('export.html', views=[fig]) return fig
def get(self, request, format=None): """Get route for entertainment map.""" gmaps.configure(api_key=os.environ.get('MAPS_API')) locations = [] for each in Entertainment.objects.all(): temp = [] p = re.compile('[()°,]') # I know this is bad regex split_location = p.sub('', str(each.location)).split() try: if split_location[0] != 'None' or split_location[1] != 'None': temp.append(float(split_location[0])) temp.append(float(split_location[1])) locations.append(temp) except IndexError: pass heatmap_layer = gmaps.heatmap_layer(locations) heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 178, 102, 0.4), (255, 128, 0, 0.8)] fig = gmaps.figure() fig.add_layer(heatmap_layer) embed_minimal_html('export.html', views=[fig]) export = open('export.html').read() return Response(export)
def show_widget(widget, title="widget"): #??? path = os.getcwd() + ".plot/" if not os.path.exists(path): os.makedirs(path) file = path + "temp.html" embed_minimal_html(file, views=[widget], title=title) webbrowser.open_new_tab(file)
def get(self, request, format=None): """Get route for crime map.""" gmaps.configure(api_key=os.environ.get('MAPS_API')) locations = [] for each in Crimes.objects.all(): temp = [] temp.append(each.latitude) temp.append(each.longitude) locations.append(temp) try: heatmap_layer = gmaps.heatmap_layer(locations) except TraitError: heatmap_layer = gmaps.heatmap_layer( [[47.465568160532435, -122.50131030799446]]) heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 105, 180, 0.4), (255, 0, 0, 0.8)] fig = gmaps.figure() fig.add_layer(heatmap_layer) embed_minimal_html('export.html', views=[fig]) export = open('export.html').read() return Response(export)
def render_locally(self, addr="localhost", server_port=8080, open_webbrowser=False, render_engine="threejs", resolution=(1800, 900)): from OCC.Display.WebGl.simple_server import start_server if render_engine == "xdom": from OCC.Display.WebGl import x3dom_renderer my_renderer = x3dom_renderer.X3DomRenderer() # TODO: Find similarities in build processing as done for THREE.js (tesselate geom etc..). # my_renderer.DisplayShape(shape.profile_curve_outer.wire) # my_renderer.DisplayShape(shape.sweep_curve.wire) # my_renderer.DisplayShape(shape.geom) my_renderer.render() else: # Assume THREEJS from ipywidgets.embed import embed_minimal_html from ada.base.renderer import MyRenderer _path = pathlib.Path("temp/index.html").resolve().absolute() renderer = MyRenderer(resolution) renderer.DisplayObj(self) renderer.build_display() os.makedirs(_path.parent, exist_ok=True) embed_minimal_html(_path, views=renderer._renderer, title="Pythreejs Viewer") start_server(addr, server_port, str(_path.parent), open_webbrowser)
def building_pm_view(project_name, platform='jupyter'): assert platform == 'jupyter' or platform == 'flask' '''project_level_table_view = build_table_widget( current_level = 'project', with_subtable = True, next_level = 'member')''' member_level_table_view = build_top_table_widget(current_level='member', with_subtable=True, next_level='table', condition=project_name, condition_type='project') table_view = build_top_table_widget(current_level='table', with_subtable=False, condition=project_name, condition_type='project') tab_nest = widgets.Tab() tab_nest.children = [member_level_table_view, table_view] tab_nest.set_title(0, 'member-level information') tab_nest.set_title(1, 'table-level information') if platform == 'flask': embed_minimal_html(project_name + '.html', views=[tab_nest], title=project_name) return open(project_name + '.html').read() else: # platform == jupyter return VBox([Label(value="Project: " + project_name), tab_nest])
def get(self, request, format=None): """Get route for Dirtiness map.""" gmaps.configure(api_key=os.environ.get('MAPS_API')) locations = [] for each in Dirtiness.objects.all(): temp = [] if each.latitude and each.longitude: temp.append(each.latitude) temp.append(each.longitude) locations.append(temp) heatmap_layer = gmaps.heatmap_layer(locations) heatmap_layer.gradient = [(0, 0, 0, 0.7), (255, 178, 102, 0.4), (102, 51, 0, 0.8)] fig = gmaps.figure() fig.add_layer(heatmap_layer) embed_minimal_html('export.html', views=[fig]) export = open('export.html').read() return Response(export)
def to_html(self, path): """ This function embed the chart widget into an HTML file dumped at the inputted path location. To see more details about embeding an ipywidget see: https://ipywidgets.readthedocs.io/en/latest/embedding.html """ embed_minimal_html(path, views=[self], state=dependency_state([self]))
def gen_heat_map(x, name): locations = np.stack((x[:, 0], x[:, 1]), axis=-1) weights = x[:, 2] fig = gmaps.figure() fig.add_layer(gmaps.heatmap_layer(locations, weights=weights)) embed_minimal_html('export_{}.html'.format(name), views=[fig])
def save_as_html(self, path, **kwargs): # Snapshot data unnecessarily adds weight here, let's drop it current_snapshot = self.snapshot self.snapshot = None embed_minimal_html(path, views=[self], **kwargs) self.snapshot = current_snapshot
def bicycling(self): start = self.box_start.get() end = self.box_end.get() fig = find_path(start, end, method = 'BICYCLING') self.fig = fig information_of_route(start, end, method = 'BICYCLING') from ipywidgets.embed import embed_minimal_html embed_minimal_html('export.html', views=[fig]) import webbrowser webbrowser.open_new('export.html')
def test_minimal_features_html(self): w = pileup.Features(json="{}", build='hg19', contig='chr1', start=1, stop=20) output = StringIO() state = dependency_state(w, drop_defaults=True) embed_minimal_html(output, views=w, drop_defaults=True, state=state) content = output.getvalue() assert content.splitlines()[0] == '<!DOCTYPE html>'
def google_map(seld): from gmaps.datasets import load_dataset_as_df df_earth = load_dataset_as_df('earthquakes') # print(df_earth.head()) locations = df_earth[['latitude', 'longitude']] weights = df_earth['magnitude'] fig = gmaps.figure() fig.add_layer(gmaps.heatmap_layer(locations, weights=weights)) embed_minimal_html('jordan_map.html', views=[fig]) return fig
def save(self, outfile, **kwargs): """Save the Map to an .html file. Parameters ---------- outfile: str or file-like object The file to write the HTML output to. kwargs: keyword-arguments Extra parameters to pass to the ipywidgets.embed.embed_minimal_html function. """ embed_minimal_html(outfile, views=[self], **kwargs)
def map_input(): # make the figure global fig fig = gmaps.figure(center=new_york_coordinates, zoom_level=10) fig.add_layer(geojson_layer) fig.add_layer(heatmap_layer) # make the html file embed_minimal_html('flaskexample/templates/export.html', views=[fig]) # flask code to render index file return render_template("input.html")
def map(): if request.method == 'GET': myLoc = (float(session['latitude']), float(session['longitude'])) hospital = (float(request.args.get('lat')), float(request.args.get('lng'))) fig = gmaps.figure() layer = gmaps.directions.Directions(myLoc, hospital, mode='car') fig.add_layer(layer) uid = session['userId'] name = f"{uid}.html" embed_minimal_html("templates/" + name, views=[fig]) return render_template(name)
def test_minimal_pileup_html(self): track = pileup.Track(viz="pileup", label="myReads", source=pileup.sources.GA4GHAlignmentJson('{}')) w = pileup.PileupViewer(locus="chr17:1-250", reference="hg19", tracks=[track]) output = StringIO() state = dependency_state(w, drop_defaults=True) embed_minimal_html(output, views=w, drop_defaults=True, state=state) content = output.getvalue() assert content.splitlines()[0] == '<!DOCTYPE html>'
def predictSingle(self, imgFile, dataDir, ployGrid=None): ''' Predicts softmax ouput by trained model for single image and plots it imgFile has to look like: # eg: <gridNo>+<lat,long>+<imageNo_date>.jpg # eg: 60+48.4271513,-110.5611851+0_2009-06.jpg ''' xx,yy = self.readData([imgFile], dataDir) yp = self.model.predict(xx)[0] yn = list(map(lambda x:x/max(yp), yp)) dist, start, end = self.gridDist(ployGrid[np.argmax(yy[0])],ployGrid[np.argmax(yp)]) if ployGrid: mx = max(yn) mn = min(yn) plt.plot([start[1],end[1]], [start[0],end[0]], color='black', label="Distance: {} miles".format(round(dist,3))) for k,i in ployGrid.items(): if k==np.argmax(yy[0]): plt.plot(i[:,1],i[:,0],color='blue',label="Actual Grid", alpha=1) else: plt.plot(i[:,1],i[:,0],color='black', alpha=0.7) plt.fill(i[:,1],i[:,0],color='red', alpha=yn[k]) plt.legend(loc="lower left") plt.show() gPoly = [] gLine = gmaps.Line( start=start, end=end, stroke_color = 'blue' ) for grid, polygon in ployGrid.items(): gPoly.append(gmaps.Polygon( list(polygon), stroke_color='black', fill_color='red', fill_opacity=float(yn[grid]) )) fig = gmaps.figure(center=(39.50,-98.35), zoom_level=4) fig.add_layer(gmaps.drawing_layer(features=gPoly)) fig.add_layer(gmaps.drawing_layer(features=[gLine])) fig.add_layer(gmaps.symbol_layer([start], scale=3, fill_color='green',stroke_color='green', info_box_content='Expected')) fig.add_layer(gmaps.symbol_layer([end], scale=3, fill_color='yellow', stroke_color='yellow', info_box_content='Predicted: {}'.format(dist))) embed_minimal_html('gmap.html', views=fig) webbrowser.open('gmap.html',new=1) return dist
def map_figure(dict_results, location_near, location_cheap, lat_current, lng_current, mode): locations = [(rows_result['geometry.location.lat'], rows_result['geometry.location.lng']) for rows_result in dict_results] restaurant_info = pin_template.template(dict_results) fig = gmaps.figure() now_location = [(lat_current, lng_current)] marker_layer = gmaps.marker_layer(now_location) fig.add_layer(marker_layer) symbol_layer = gmaps.symbol_layer(locations, info_box_content=restaurant_info, scale=5, stroke_color="red") index_free = int("".join([ str(integer) for integer in [i for i in range(len(locations)) if locations[i] == location_near] ])) symbol_layer.markers[index_free].stroke_color = 'blue' google_maps_route.route((lat_current, lng_current), location_near, fig, 'blue', 5.0, mode) print( "---Results retrieved! Please, find attached an html file with the map with all the info you need.---" ) if location_near != location_cheap: index_near = int("".join([ str(integer) for integer in [ i for i in range(len(locations)) if locations[i] == location_cheap ] ])) symbol_layer.markers[index_near].stroke_color = 'green' google_maps_route.route((lat_current, lng_current), location_cheap, fig, 'green', 5.0, mode) print( "\n---The cheapest gluten free restaurant is the one marked in the blue route" " and the nearest one on the green route---\n") else: print( "\n---The nearest one is also the cheapest one! The route is marked in blue---\n" ) fig.add_layer(symbol_layer) embed_minimal_html('./maps/routes.html', views=[fig])
def main(): parser = argparse.ArgumentParser() parser.add_argument("path", type=str, help='specify path of jpg files') parser.add_argument("-T", "--type", type=str, help='select marker or heatmap', default="marker") args = parser.parse_args() if args.path == None: print(parser.print_usage) exit(0) elif os.path.exists(args.path): lista = search(args.path) imagenes = [] locations = [] for img in lista: pic = Image.open(img) info = pic._getexif() if not info is None: for (tag, value) in info.items(): tagname = TAGS.get(tag, tag) if tagname == "GPSInfo": try: if value[1] == "N" or value[1] == "S": imagenes.append(img) except KeyError as error: pass if len(imagenes) == 0: print("no jpg file contains location data") exit(0) else: for loc in imagenes: locs = gpsinfo(loc) locations.append(locs) if args.type == "marker": geopic = marker(locations) embed_minimal_html('export.html', views=[geopic]) else: geopic = heat(locations) embed_minimal_html('export.html', views=[geopic]) else: print("Path do not exist") exit(0)
def aois_on_gmaps_html(self): aois = gpd.read_file("static/aois.geojson") aois = aois.to_crs({'init': 'epsg:4326'}) figure_layout = { 'width': '100%', 'height': '50em', } fig = gmaps.figure(center=[47.372, 8.541], zoom_level=16, layout=figure_layout) geojson_layer = gmaps.geojson_layer(geojson.loads(aois.to_json()), fill_opacity=0.01) fig.add_layer(geojson_layer) fig embed_minimal_html('/tmp/export.html', views=[fig]) with open('/tmp/export.html') as f: return f.read()
def prediction(filename, location): output_list = [] image_file = filename location_input = location print(location_input) predicted_word = output(image_file) geolocator = Nominatim(user_agent="Natural Disaster") location = geolocator.geocode(location_input) print(("Location Latitude, Longitude", location.latitude, location.longitude)) print("predicted_word", predicted_word) latitude = location.latitude longitude = location.longitude if os.path.isfile("run_demo.pickle"): output_list = pickle.load(open("run_demo.pickle", "rb")) output_list.append( (image_file, location.latitude, location.longitude, predicted_word)) gmaps.configure(api_key="AIzaSyA8QY3k_68BaSlDTehnWd0Kf73h5z7cIjA") fig = gmaps.figure(map_type="SATELLITE") for image, lat, lon, prediction in output_list: color = "" if (prediction == "severe"): color = 'red' elif (prediction == "mild"): color = "yellow" else: color = "green" layer = gmaps.symbol_layer([(lat, lon)], fill_color=color, stroke_color=color, hover_text="location_input") fig.add_layer(layer) pickle.dump(output_list, open("run_demo.pickle", "wb")) new_name = os.getcwd() + '/templates/' + 'export.html' embed_minimal_html(new_name, views=[fig])
def building_admin_view(platform='jupyter'): assert platform == 'jupyter' or platform == 'flask' project_level_table_view = build_top_table_widget(current_level='project', with_subtable=True, next_level='member') member_level_table_view = build_top_table_widget(current_level='member', with_subtable=True, next_level='table') table_view = build_top_table_widget(current_level='table') tab_nest = widgets.Tab() tab_nest.children = [ project_level_table_view, member_level_table_view, table_view ] tab_nest.set_title(0, 'project-level information') tab_nest.set_title(1, 'member-level information') tab_nest.set_title(2, 'table-level information') if platform == 'flask': embed_minimal_html('db_admin.html', views=[tab_nest], title='DB Admin') return open('db_admin.html').read() else: # platform == jupyter return tab_nest
def map_output(): # get address info user_input = request.args.get('input_address') address = user_input address += "; NY" address_coords = geocoder.google(address, key=api_key) address_point_df = pd.DataFrame(data={'geometry': \ [Point(address_coords.latlng[1], address_coords.latlng[0])]}) address_point_map = gpd.GeoDataFrame(address_point_df, geometry='geometry', crs=nbhd_map.crs) combined = gpd.tools.sjoin(address_point_map, nbhd_map, how='left') if combined.isna().loc[0,'Neighborho']: return render_template("error.html") else: address_dict = [{'input_address': user_input, 'nbhd': combined.loc[0, 'Neighborho'], 'location': (address_coords.latlng[0], address_coords.latlng[1])}] info_box_template = """ <dl> <dt>Address</dt><dd>{input_address}</dd> <dt>Neighborhood</dt><dd>{nbhd}</dd> </dl> """ address_info = [info_box_template.format(**address) for address in address_dict] address_location = [address['location'] for address in address_dict] marker_layer = gmaps.marker_layer(address_location, info_box_content=address_info, hover_text='Click for Information') # add to the figure fig.add_layer(marker_layer) # make the html map file embed_minimal_html('flaskexample/templates/export_marker.html', views=[fig]) # flask code to render output file return render_template("output.html")
def heatmap(x): #Configure gmaps with API key gmaps.configure(api_key=gkey) #Removing NAN values temp_df = data_df[[x, 'Latitude', 'Longitude']].dropna() weights = temp_df[x].astype(float) fig = gmaps.figure() # Create heatmap layer heatmap = gmaps.heatmap_layer(temp_df[['Latitude', 'Longitude']], weights=weights) # Set heatmap format, use quartiles to set the max intensity for all upper outliers heatmap.max_intensity = (float(weights.quantile([.75])) * 2.5) - (float(weights.quantile([.25])) * 1.5) heatmap.dissipating = False heatmap.point_radius = .25 # Create and Save Figure fig.add_layer(heatmap) embed_minimal_html(f'Output/Heatmaps/{x}.html', views=[fig])
gmaps.configure(api_key="AIzaSyCo99awBRG0JvRCoJC8M12-3EiAoLfElSM") fig = gmaps.figure() from PIL import Image im = Image.open("/Users/Aakash/36.070403, 68.629560, 68.673354.png") inputim = im.filter(ImageFilter.ModeFilter(8)) inputim.show() pix = inputim.load() imout = im.copy() pixout = imout.load() deltax = 68.673354 - 68.629560 locations = [] xlist = [] ylist = [] for i in range(0, inputim.size[0], 8): #x-axis search for j in range(0, inputim.size[1], 8): #y-axis search if pix[i, j][1] > 140: pixout[i, j] = (255, 0, 0) xlist = xlist + [-j / 1000 * delta + 36.070403] ylist = ylist + [i / 1000 * delta + 68.629560] for k in range(0, len(xlist), 5): locations = locations + [(xlist[k], ylist[k])] imout.show() marker = gmaps.marker_layer(locations) fig.add_layer(marker) embed_minimal_html('export3.html', views=[fig])
def predictSingle(self, imgFile, dataDir, ployGrid): ''' Predicts softmax ouput by trained model for single image and plots it mgFiles: String that contains test location image triplet folder name. String has to look like: # <gridNo>+<lat,long> # 60+48.4271513,-110.5611851 dataDir: Directory that stores combined image files eg: "/dataCombinedSamples/" polyGrid: List of polygons that contain make up the USA split into grids. It can be loaded from eg: "infoExtraction/usaPolyGrid.pkl" ''' # read image triplets from single file xx, yy = self.readData([imgFile], dataDir) # predict single image triplet yp = self.model.predict(xx)[0] # normalize prediction for better visualization yn = list(map(lambda x: x / max(yp), yp)) # evaluate distance for single point dist, start, end = self.gridDist(ployGrid[np.argmax(yy[0])], ployGrid[np.argmax(yp)]) mx = max(yn) mn = min(yn) # plot result using matplotlib plt.plot([start[1], end[1]], [start[0], end[0]], color='black', label="Distance: {} miles".format(round(dist, 3))) for k, i in ployGrid.items(): if k == np.argmax(yy[0]): plt.plot(i[:, 1], i[:, 0], color='blue', label="Actual Grid", alpha=1) else: plt.plot(i[:, 1], i[:, 0], color='black', alpha=0.7) plt.fill(i[:, 1], i[:, 0], color='red', alpha=yn[k]) plt.legend(loc="lower left") plt.show() # plot result using google maps API gPoly = [] gLine = gmaps.Line(start=start, end=end, stroke_color='blue') for grid, polygon in ployGrid.items(): gPoly.append( gmaps.Polygon(list(polygon), stroke_color='black', fill_color='red', fill_opacity=float(yn[grid]))) fig = gmaps.figure(center=(39.50, -98.35), zoom_level=4) fig.add_layer(gmaps.drawing_layer(features=gPoly)) fig.add_layer(gmaps.drawing_layer(features=[gLine])) fig.add_layer( gmaps.symbol_layer([start], scale=3, fill_color='green', stroke_color='green', info_box_content='Expected')) fig.add_layer( gmaps.symbol_layer([end], scale=3, fill_color='yellow', stroke_color='yellow', info_box_content='Predicted: {}'.format(dist))) # save and display html page containing google maps API embed_minimal_html('gmap.html', views=fig) webbrowser.open('gmap.html', new=1) return dist
%load_ext autoreload %autoreload 2 from new_notebook import NotebookCreatorWidget NotebookCreatorWidget() from ipywidgets import IntSlider from ipywidgets.embed import embed_minimal_html slider = IntSlider(value=40) embed_minimal_html('export.html', views=[NotebookCreatorWidget()], title='Widgets export') import ipywidgets.embed
def cytoscape_graph( dsk, filename: str | None = "mydask", format: str | None = None, *, rankdir: str = "BT", node_sep: float = 10, edge_sep: float = 10, spacing_factor: float = 1, node_style: dict[str, str] | None = None, edge_style: dict[str, str] | None = None, **kwargs, ): """ Create an ipycytoscape widget for a dask graph. If `filename` is not None, write an HTML file to disk with the specified name. This uses the Cytoscape dagre layout algorithm. Options for that are documented here: https://github.com/cytoscape/cytoscape.js-dagre#api Parameters ---------- dsk : dict The graph to display. filename : str or None, optional The name of the HTML file to write to disk. format : str, optional Not used in this engine. rankdir: str The direction in which to orient the visualization. node_sep: float The separation (in px) between nodes in the DAG layout. edge_sep: float The separation (in px) between edges in the DAG layout. spacing_factor: float An overall scaling factor to increase (>1) or decrease (<1) the spacing of the layout. node_style: dict[str, str], optional A dictionary of style attributes for nodes (refer to Cytoscape JSON docs for available options: https://js.cytoscape.org/#notation/elements-json) edge_style: dict[str, str], optional A dictionary of style attributes for edges (refer to Cytoscape JSON docs for available options: https://js.cytoscape.org/#notation/elements-json) **kwargs Additional keyword arguments to forward to `_to_cytoscape_json`. Returns ------- result : ipycytoscape.CytoscapeWidget """ ipycytoscape = import_required( "ipycytoscape", "Drawing dask graphs with the cytoscape engine requires the `ipycytoscape` " "python library.\n\n" "Please either conda or pip install as follows:\n\n" " conda install ipycytoscape # either conda install\n" " python -m pip install ipycytoscape # or pip install", ) node_style = node_style or {} edge_style = edge_style or {} data = _to_cytoscape_json(dsk, **kwargs) # TODO: it's not easy to programmatically increase the height of the widget. # Ideally we would make it a bit bigger, but that will probably require upstreaming # some fixes. g = ipycytoscape.CytoscapeWidget( layout={"height": "400px"}, ) g.set_layout( name="dagre", rankDir=rankdir, nodeSep=node_sep, edgeSep=edge_sep, spacingFactor=spacing_factor, nodeDimensionsIncludeLabels=True, ) g.graph.add_graph_from_json( data, directed=True, ) g.set_style( [ { "selector": "node", "style": { "font-family": "helvetica", "font-size": "24px", "font-weight": "bold", "color": "black", "background-color": "#eee", "border-color": "data(color)", "border-width": 4, "opacity": "1.0", "text-valign": "center", "text-halign": "center", "label": "data(label)", "shape": "data(shape)", "width": 64, "height": 64, **node_style, }, }, { "selector": "edge", "style": { "width": 8, "line-color": "gray", "target-arrow-shape": "triangle", "target-arrow-color": "gray", "curve-style": "bezier", **edge_style, }, }, ], ) # Tweak the zoom sensitivity z = g.zoom g.max_zoom = z * 2.0 g.min_zoom = z / 10.0 g.wheel_sensitivity = 0.1 if filename is not None: from ipywidgets.embed import embed_minimal_html filename = filename if filename.endswith(".html") else filename + ".html" embed_minimal_html(filename, views=[g], title="Dask task graph") return g