コード例 #1
0
 def _hvplot_trajectory(self, traj):
     line_gdf = self._make_line_df(traj)
     if self.hvplot_is_geo and not traj.is_latlon and traj.crs is not None:
         line_gdf = line_gdf.to_crs(epsg=4326)
     if self.column and isinstance(self.column, str):
         self.kwargs["c"] = dim(
             self.column
         )  # fixes https://github.com/anitagraser/movingpandas/issues/71
     if self.column and self.colormap:
         try:
             color = self.colormap[traj.df[self.column].max()]
         except KeyError:
             color = "grey"
         return line_gdf.hvplot(
             color=color,
             geo=self.hvplot_is_geo,
             tiles=self.hvplot_tiles,
             label=traj.df[self.column].max(),
             *self.args,
             **self.kwargs
         )
     else:
         return line_gdf.hvplot(
             geo=self.hvplot_is_geo,
             tiles=self.hvplot_tiles,
             *self.args,
             **self.kwargs
         )
コード例 #2
0
ファイル: holoviews.py プロジェクト: dhimmel/kh-tools
def draw_holoviews_graphs(graph_dict):
    # use first key to determine default settings
    first_key = list(graph_dict.keys())[0]
    molecule, ksize, log2sketchsize = first_key

    hv.extension('bokeh')
    defaults = dict(width=400, height=400, padding=0.1)
    hv.opts.defaults(opts.EdgePaths(**defaults), opts.Graph(**defaults),
                     opts.Nodes(**defaults))

    kdims = [
        hv.Dimension(('molecule', "molecule"), default=molecule),
        hv.Dimension(('ksize', "k-mer size"), default=ksize),
        hv.Dimension(('log2_num_hashes', "$\log_2$ num hashes"),
                     default=log2sketchsize),
    ]

    kwargs = dict(width=800, height=800, xaxis=None, yaxis=None)
    opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs))

    kwargs = dict(node_size=10,
                  edge_line_width=1,
                  cmap='Set2',
                  node_color=dim("species"),
                  node_line_color='gray',
                  width=600,
                  height=600,
                  xaxis=None,
                  yaxis=None)

    holomap = hv.HoloMap(graph_dict, kdims=kdims)
    holomap.opts(opts.Graph(**kwargs))
    return holomap
コード例 #3
0
def __size_legend(size_min, size_max, dot_min, dot_max,
                  size_tick_labels_format, size_ticks):
    size_ticks_pixels = np.interp(size_ticks, (size_min, size_max),
                                  (dot_min, dot_max))
    size_tick_labels = [size_tick_labels_format.format(x) for x in size_ticks]
    points = hv.Points(
        {
            'x': np.repeat(0.15, len(size_ticks)),
            'y': np.arange(len(size_ticks), 0, -1),
            'size': size_ticks_pixels
        },
        vdims='size').opts(xaxis=None,
                           color='black',
                           yaxis=None,
                           size=dim('size'))
    labels = hv.Labels(
        {
            'x': np.repeat(0.3, len(size_ticks)),
            'y': np.arange(len(size_ticks), 0, -1),
            'text': size_tick_labels
        }, ['x', 'y'], 'text').opts(text_align='left', text_font_size='9pt')
    overlay = (points * labels)
    overlay.opts(width=dot_max + 100,
                 height=int(len(size_ticks) * (dot_max + 12)),
                 xlim=(0, 1),
                 ylim=(0, len(size_ticks) + 1),
                 invert_yaxis=True,
                 shared_axes=False,
                 show_frame=False)
    return overlay
コード例 #4
0
def make_plot(weight_field):
    return edges_plot.opts(clone = True, node_color = "type", node_line_width=0, node_size = hv.dim("type").categorize(node_type_size_dict),
                node_cmap="Category10_r",
                edge_color=weight_field,edge_alpha=.9,
                edge_line_width = 1.5*hv.dim(weight_field).norm()+.3,
                edge_cmap="Reds", xaxis=None, yaxis=None, width=1000, height=800,
                colorbar=True,  inspection_policy="edges" ,bgcolor="#282829")*labels
コード例 #5
0
def create_figure(x, y, color, size):
    opts = dict(cmap='rainbow', width=800, height=600, line_color='black')
    if color != 'None':
        opts['color'] = color 
    if size != 'None':
        opts['size'] = hv.dim(size).norm()*20
    return hv.Points(df, [x, y], label="%s vs %s" % (x.title(), y.title())).opts(**opts)
コード例 #6
0
def modify_doc(doc, mytabs):

	start, end = 1, 20
	samples_count = 5
	slider = Slider(start=start, end=end, value=start, step=1, title="Counts")
	select = Select(title="Count", value="aux", options=["box", "pack", "image", "user"])

	renderer = hv.renderer('bokeh')##.instance(mode='server')
	hv.extension('bokeh')
	hv.output(size=200)
	links = pd.DataFrame(data['links'])
	print(links.head(3))
	nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
	chord = hv.Chord((links, nodes)).select(value=(samples_count, None))
	chord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), labels='name', node_color=dim('index').str()))    	
	# Create HoloViews plot and attach the document
	hvplot = renderer.get_plot(chord, doc)
	
	def slider_update(attrname, old, new):
		# Notify the HoloViews stream of the slider update 
		print ("update received")
		samples_count = new
		
		links = pd.DataFrame(data['links'])
		print(links.head(3))
		nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
		chord = hv.Chord((links, nodes)).select(value=(samples_count, None))
		chord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), labels='name', node_color=dim('index').str()))    	
		# Create HoloViews plot and attach the document
		hvplot = renderer.get_plot(chord, doc)
		tab3 = Panel(child=row(slider, hvplot.state), title="Chord Plot")

		mytabs.append(tab3)
		views = Tabs(tabs = mytabs)
		layout=row(views)
		doc.add_root(layout)
	
		return doc

	slider.on_change('value', slider_update)

	
	def select_update(attrname, old, new):
		# Notify the HoloViews stream of the slider update 
		print ("update received. Old: {} New: {}".format(old, new))
		

	select.on_change('value', select_update)		

	# Combine the holoviews plot and widgets in a layout

	tab3 = Panel(child=row(slider, hvplot.state), title="Chord Plot")

	mytabs.append(tab3)
	views = Tabs(tabs = mytabs)
	layout=row(views)
	doc.add_root(layout)
	
	return doc
コード例 #7
0
 def chord(data):
     hv.extension('bokeh')
     renderer = hv.renderer('bokeh')
     hv.output(size=230)
     links = pd.DataFrame(data['links'])
     hv.Chord(links)
     nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
     chord = hv.Chord((links, nodes)).select(value=(10, None))
     chord.opts(
         opts.Chord(cmap='Category20',
                    edge_cmap='Category20',
                    edge_color=dim('source').str(),
                    labels='name',
                    node_color=dim('index').str()))
     bokeh_plot = renderer.get_plot(chord).state
     html = file_html(bokeh_plot, CDN, "my plot")
     return html
コード例 #8
0
    def hvplot(self, ptype="shape"):
        """
        Plots the shape (Notices, it requries holoviews)
        Parameters
        ----------
        :param ptype str: Plot type. The following are excepted:
        "shape": Plots the shape-edges with equal aspect-ratio
        "vectors": Plots shape-edges, as well as panel-centers and tangential and normal vectors.
        """
        try:
            import holoviews as hv
        except ImportError:
            raise ImportError(
                "To use the plot method holoviews is requried, see more here: http://holoviews.org/"
            )

        if ptype == "shape":
            # Shape of airfoil (edges)
            return hv.Curve(self.xy).opts(aspect='equal',
                                          width=1000,
                                          height=500,
                                          padding=0.1)
        elif ptype == "vectors":
            # Vectors at panel centeres
            pc = hv.Scatter(np.array([self.px, self.py]).T,
                            kdims="px",
                            vdims="py").opts(size=5)
            vf = hv.VectorField(np.array(
                [self.px, self.py,
                 np.angle(self.tan),
                 np.abs(self.tan)]).T,
                                label="Tangent")
            vf.opts(rescale_lengths=False,
                    magnitude=hv.dim('Magnitude') * 0.01 * self.scale,
                    pivot="tail")
            vfnor = hv.VectorField(np.array(
                [self.px, self.py,
                 np.angle(self.nor),
                 np.abs(self.nor)]).T,
                                   label="Normal")
            vfnor.opts(rescale_lengths=False,
                       magnitude=hv.dim('Magnitude') * 0.01 * self.scale,
                       pivot="tail",
                       color="red")  # , label="Normal")
            return self.plot("shape") * pc * vf * vfnor
コード例 #9
0
ファイル: interactive.py プロジェクト: wsheffel/hvplot
 def _plot(self, *args, **kwargs):
     @pn.depends()
     def get_ax():
         from matplotlib.backends.backend_agg import FigureCanvas
         from matplotlib.pyplot import Figure
         Interactive._fig = fig = Figure()
         FigureCanvas(fig)
         return fig.subplots()
     kwargs['ax'] = get_ax
     transform = hv.dim(self._transform, 'plot', accessor=True)
     return self._clone(transform(*args, **kwargs), plot=True)
コード例 #10
0
 def test_pandas_transform(self):
     demo_df = pd.DataFrame({
         'value': np.random.randn(50),
         'probability': np.random.rand(50)
     })
     percent = hv.dim('probability') * 100
     scatter = demo_df.hvplot.scatter(x='value',
                                      y='probability',
                                      transforms=dict(probability=percent))
     self.assertEqual((scatter.data['probability']).values,
                      demo_df['probability'].values * 100)
コード例 #11
0
    def plot_hits(self, data):
        """
		This function controls evolution of hits on detector geometry. Color represents the time of hit and 
		the size of circle represents the size of signal on antennae. But the size of circle and
		the strength of electric field/voltage on antennae are not directly related.
		
		Hits to be plotted are binned in time so that hits are evolved in a reasonable speed. 
		Note that the provided antennae information (x,y,t) are already sorted based by time of hit.

		'data' is sent here from 'animate' function inside a while loop.
		"""
        x = data[0]  # updated x-coordinate of hit tanks to be plotted.
        y = data[1]  # updated y-coordinate of hit tanks to be plotted.
        t = data[2]  # updated hit time of hit tanks to be plotted.
        wt = data[3]  # updated weight of hit tanks to be plotted.
        color = data[4]  # updated colors to represent time of hit.
        kdims = ['X', 'Y']
        vdims = ['Weight', 'Time', 'Color']
        if len(
                x
        ) == 0:  # if empty data is sent, this prevents code to fail and plots empty hits.
            fig = hv.Points([], kdims=kdims, vdims=vdims)
            fig.opts(
                opts.Points(width=main_width,
                            height=main_height,
                            tools=['hover']))
        else:
            pd_data = pd.DataFrame(
                data={
                    'X': x / 1.e3,  # m --> km.
                    'Y': y / 1.e3,  # m --> km.
                    'Weight': wt,
                    'Time': t,
                    'Color': color
                })

            ds = hv.Dataset(
                pd_data)  # create a holoview dataset from pandas dataframe.
            '''This is the part where hits are plotted. This function is called many times and number of 
			hits are added in each call until all hits are included.'''
            fig = hv.Points(ds, kdims=kdims, vdims=vdims)
            '''Add options to the plot.'''
            fig.opts(
                opts.Points(
                    width=main_width,
                    height=main_height,
                    size=np.log(dim('Weight')) *
                    4.,  # signal strenght. This is arbitrary.
                    marker='circle',
                    color='Color',
                    alpha=0.95,
                    tools=['hover']))
        return fig
コード例 #12
0
def plot_chord(predictions, filename):
    to_use = predictions.copy()
    for n, row in predictions.iterrows():
        if row.MLSynergy_score < 0:
            to_use.at[n, "MLSynergy_score"] = row.MLSynergy_score * -1
            to_use.at[n, "Interaction"] = "Synergy"
        else:
            to_use.at[n, "Interaction"] = "Antagony"
    hv.extension('bokeh')
    hv.output(size=200)
    to_use2 = to_use[to_use.NumbDrugs == 2]
    links = to_use2[["Drug1", "Drug2", "MLSynergy_score", "Interaction"]]
    drugs = list(links["Drug1"].unique()) + list(links["Drug2"].unique())
    nodes = hv.Dataset(drugs, 'Drug')
    chord = hv.Chord((links, nodes)).select(value=(1, None))
    chord.opts(opts.Chord(cmap='Rainbow', edge_cmap='Rainbow',\
                          edge_color=dim('Interaction').str(), labels='Drug',\
                          node_color=dim('Drug').str()))
    output_file(filename)
    show(hv.render(chord))
    return to_use2
コード例 #13
0
ファイル: __init__.py プロジェクト: pygridgen/hologridgen
    def __init__(self, data=None, **params):
        data_params = {} if data is None else {k:v for k,v in data.items()
                                               if k not in self._columns}
        params = dict(data_params, **params)
        data = {k:[] for k in self._columns} if (data is None) else data
        super().__init__(**params)

        def install_handle(plot, element):
            "Handle needed to make the draw_tool available in the JS callback"
            plot.handles['draw_tool'] = plot.state.tools[-1]

        node_style = dict(self.node_style,
                           tools=['tap'],
                           color=hv.dim('polarity'),
                           fill_alpha=hv.dim('polarity').categorize({'0':0, '+':1, '-':1 }),
                           show_legend=False, hooks=[install_handle])

        # PointDraw Stream that enables the PointDraw Bokeh tool
        self._node_stream = hv.streams.PointDraw(data=data,
                                                 num_objects=self.max_nodes,
                                                 empty_value = '+')

        # Nodes is a DynamicMap returning hv.Points along the boundary
        self.nodes = hv.DynamicMap(self.points,
                                  streams=[self._node_stream,
                                           self.param.insert_points,
                                           self.param.node_size]).opts(**node_style)
        # DynamicMap drawing the boundary as a hv.Path element
        self.boundary_dmap = hv.DynamicMap(self._boundary,
                                         streams=[self._node_stream,
                                                  hv.streams.Selection1D()])
        # DynamicMap placing the start indicator
        self.start_marker = hv.DynamicMap(self._start_marker,
                                          streams=[self._node_stream]
                                          ).opts(**self.start_indicator_style)

        # Initial, empty mesh
        self.qmesh = hv.QuadMesh((np.zeros((2,2)), np.zeros((2,2)), np.zeros((2,2))))

        self._selected_edge_index = None
コード例 #14
0
ファイル: interactive.py プロジェクト: wsheffel/hvplot
 def __init__(self, obj, transform=None, plot=False, depth=0,
              loc='top_left', center=False, dmap=False, inherit_kwargs={},
              **kwargs):
     self._obj = obj
     self._method = None
     if transform is None:
         import xarray as xr
         if isinstance(obj, xr.DataArray):
             self._transform = hv.dim(obj.name)
         else:
             self._transform = hv.dim('*')
     else:
         self._transform = transform
     self._plot = plot
     self._depth = depth
     self._loc = loc
     self._center = center
     self._dmap = dmap
     self._inherit_kwargs = inherit_kwargs
     self._kwargs = kwargs
     ds = hv.Dataset(self._obj)
     self._current = self._transform.apply(ds, keep_index=True, compute=False)
コード例 #15
0
 def test_xarray_transform(self):
     import xarray as xr
     data = np.arange(0, 60).reshape(6, 10)
     x = np.arange(10)
     y = np.arange(6)
     da = xr.DataArray(data,
                       coords={
                           'y': y,
                           'x': x
                       },
                       dims=('y', 'x'),
                       name='value')
     img = da.hvplot.image(transforms=dict(value=hv.dim('value') * 10))
     self.assertEqual(img.data.value.data, da.data * 10)
コード例 #16
0
def node_tab(filename):
    G = scripts.MakeNetworkxGraph.__makegraph__(sep_type='semicolon',
                                                nodes_df_link=filename)
    """ Make HV network """
    hv_graph = hv.Graph.from_networkx(G, nx.spring_layout,
                                      k=1).relabel('Force-Directed Spring')

    hv_graph.opts(width=650,
                  height=650,
                  xaxis=None,
                  yaxis=None,
                  padding=0.1,
                  node_size=hv.dim('size'),
                  node_color=hv.dim('node_type'),
                  cmap='YlOrBr',
                  edge_color=hv.dim('weight'),
                  edge_cmap='YlGnBu',
                  edge_line_width=hv.dim('weight'))

    # Output files to Flask
    renderer = hv.renderer('bokeh')
    plot = renderer.get_plot(hv_graph, show=True).state

    return plot
コード例 #17
0
def bokeh_fig(year):
    df = gapminder.query("year == %d" % (year or 1952))
    return json_item(
        hv.render(
            hv.Points(df,
                      kdims=["gdpPercap",
                             "lifeExp"]).opts(color="continent",
                                              size=hv.dim("pop")**(0.5) / 800,
                                              logx=True,
                                              height=330,
                                              width=530,
                                              cmap="Category10",
                                              tools=["hover"],
                                              legend_position="bottom_right",
                                              title="HoloViews / Bokeh")))
コード例 #18
0
    def __init__(self, path, ping_file_path, speed_test_file_path):

        self.path = path
        self.ping_file_path = ping_file_path
        self.speed_test_file_name = speed_test_file_path

        # Define default layout of graphs
        hv.extension('bokeh')

        opts.defaults(
            opts.Bars(xrotation=45, tools=['hover']),
            opts.BoxWhisker(width=700, xrotation=30, box_fill_color=Palette('Category20')),
            opts.Curve(width=700, tools=['hover']),
            opts.GridSpace(shared_yaxis=True),
            opts.Scatter(width=700, height=500, color=Palette('Category20'), size=dim('growth')+5, tools=['hover'],alpha=0.5, cmap='Set1'),
            opts.NdOverlay(legend_position='left'))

        if os.path.isdir(os.path.join(self.path, "webpage","figures")) is False:
            os.mkdir(os.path.join(self.path, "webpage","figures"))
            print("Path 'figures' created successfully")
        else:
            print("Path 'figures' initialized")
        # Load basic configurations
        config = configparser.ConfigParser()

        try:
            config.read('./modules/config_a.ini')
            # Get values from configuration file
            self.upper_acceptable_ping_bound = float(config['DEFAULT']['upper_acceptable_ping_bound'])
            self.upper_ping_issue_bound = float(config['DEFAULT']['upper_ping_issue_bound'])
            self.acceptable_network_speed = float(config['DEFAULT']['acceptable_network_speed'])
        except:
            # In case no config-file is found or another reading error occured
            print("Configuration file not found/readable.")
            print("Creating a new configuration file.")
            # Creating new file with standard values
            config['DEFAULT'] = {'upper_acceptable_ping_bound': '10',
                                 'upper_ping_issue_bound': '99999',
                                 'acceptable_network_speed': '16'}
            with open('config_a.ini', 'w') as configfile:
                config.write(configfile)
            print("New configuration file was created. Running on default parameters, please restart for changes.")

            #set default values to continue with program
            self.upper_acceptable_ping_bound = float(config['DEFAULT']['upper_acceptable_ping_bound'])
            self.upper_ping_issue_bound = float(config['DEFAULT']['upper_ping_issue_bound'])
            self.acceptable_network_speed = float(config['DEFAULT']['acceptable_network_speed'])
コード例 #19
0
ファイル: interactive.py プロジェクト: wsheffel/hvplot
 def __getattr__(self, name):
     if name in dir(self):
         if self._method:
             transform = hv.dim(self._transform, self._method, accessor=True)
             inherit_kwargs = {}
             if self._method == 'plot':
                 inherit_kwargs['ax'] = self._get_ax_fn()
             new = self._clone(transform, inherit_kwargs=inherit_kwargs)
         else:
             new = self
         new._method = name
         try:
             new.__doc__ = getattr(new, name).__doc__
         except Exception:
             pass
         return new
     raise AttributeError(name)
コード例 #20
0
def create_artists_points(data):
    artists_tooltips = """
        <div>
            <div>
                <img
                    src="@image" height="70" alt="@image" width="70"
                    style="float: left; margin: 0px 15px 15px 0px;"
                    border="1"
                ></img>
            </div>
            <div>
                <span style="font-size: 15px;"><b>@name</b></span>
            </div>
            <div>
                <span style="font-weight: bold;">Main genre:</span>
                <span>@genre_cluster</span>
            </div>
            <div>
                <span style="font-weight: bold;">Subgenre:</span>
                <span>@genre_specific</span>
            </div>
        </div>
    """
    artists_hover = HoverTool(tooltips=artists_tooltips)
    artists_points = hv.Points(data=data,
                               kdims=["genre_x", "genre_y"],
                               vdims=[
                                   "genre_cluster", "genre_specific",
                                   "popularity", "image", "name"
                               ])
    artists_points.opts(
        tools=["box_select", "lasso_select", artists_hover, "tap"],
        color="genre_cluster",
        cmap="dark2",
        line_color="black",
        size=hv.dim("popularity") / 5,
        padding=0.1,
        width=800,
        height=600,
        show_grid=False,
        show_frame=False,
        xaxis="bare",
        yaxis="bare",
        title="Artists")
    return artists_points
コード例 #21
0
def generateGraph(choice):
    value_dim = hv.Dimension('Percentage', unit='%')
    if choice == 'Feelings about Future':
        sankey = hv.Sankey((fearEdges,fearNodes), ['From','To'], vdims=value_dim)
        #sankey = hv.Sankey([(fearTable[i],fearTable[j],k) for i,j,k in fearEdges], ['From','To'], vdims=value_dim)
        sankey.opts(title='How Tech Savviness Influences Feelings about Connectivity')
    elif choice == 'Importance Rankings':
        sankey = hv.Sankey((rankEdges,rankNodes), ['From','To'], vdims=value_dim)
        #sankey = hv.Sankey([(rankTable[i],rankTable[j],k) for i,j,k in rankEdges], ['From','To'], vdims=value_dim)
        sankey.opts(title='How Tech Savviness Influences Priorities when Purchasing New Devices')
    sankey.opts(labels='label',
                width=1000,
                height=900,
                cmap=jankyCmap,
                edge_color=dim('From').str(),
                fontsize={'title': 18, 'labels': 16},
                node_hover_fill_color='grey',
                tools=[hover])
    return sankey
コード例 #22
0
    def ChordDiagram(self):
        # Step 1 Get Data
        self.sharedNeos = self.GetShared()
        self.matchedNeos = self.GetMatchedNeos()

        hv.output(size=200)

        source = []
        target = []
        value = []
        for i, sam in enumerate(self.sharedNeos):
            for pair in self.sharedNeos[sam]:
                source.append(sam + "_" + pair.split(',')[0])
                target.append(sam + "_" + pair.split(',')[1])
                value.append(self.sharedNeos[sam][pair])

        for matched in self.matchedNeos:
            source.append(matched.split(',')[0])
            target.append(matched.split(',')[1])
            value.append(self.matchedNeos[matched])

        links = pd.DataFrame({
            'source': source,
            'target': target,
            'value': value
        })

        chord = hv.Chord(links)

        # chord = hv.Chord((links, nodes)).select(value=(5, None))
        chord.opts(
            opts.Chord(cmap='Category20',
                       edge_cmap='Category20',
                       labels='index',
                       node_color=dim('index').str()))

        p = hv.render(chord)

        select = Select(title="Option:",
                        value="foo",
                        options=["foo", "bar", "baz", "quux"])

        return (p, select)
コード例 #23
0
def plot_player_ratings_scatter(
    player_ratings: pd.DataFrame,
    x_col: str,
    y_col: str,
    color_col: str = "overall",
    size_col: str = "overall",
    **plot_opts,
) -> hv.Overlay:
    scatter_base = (player_ratings.reset_index().hvplot.scatter(
        x=x_col,
        y=y_col,
        c=color_col,
        hover_cols=["name", "overall"],
    ).opts(
        size=abs(dim(size_col)) * 2,
        **plot_opts,
    ))
    overlay = (scatter_base * hv.VLine(0).opts(color="gray") *
               hv.HLine(0).opts(color="gray"))
    return overlay
コード例 #24
0
	def slider_update(attrname, old, new):
		# Notify the HoloViews stream of the slider update 
		print ("update received")
		samples_count = new
		
		links = pd.DataFrame(data['links'])
		print(links.head(3))
		nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
		chord = hv.Chord((links, nodes)).select(value=(samples_count, None))
		chord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), labels='name', node_color=dim('index').str()))    	
		# Create HoloViews plot and attach the document
		hvplot = renderer.get_plot(chord, doc)
		tab3 = Panel(child=row(slider, hvplot.state), title="Chord Plot")

		mytabs.append(tab3)
		views = Tabs(tabs = mytabs)
		layout=row(views)
		doc.add_root(layout)
	
		return doc
コード例 #25
0
def era5_static(era5_data, hour, wind):
    """
    Static wind vectorfield at specific hour and height (10/100m)
    
    """
    if wind == 10:
        angle = 'rad_10'
        mag = 'intensity_10'
    else:
        angle = 'rad_100'
        mag = 'intensity_100'

    return (era5_data.sel(Time=str(im[0][0].value) +
                          'T{hour:02d}'.format(hour=hour)).hvplot.vectorfield(
                              x='lon',
                              y='lat',
                              angle=angle,
                              mag=mag,
                              hover=False)).opts(magnitude=dim(mag) * 0.01,
                                                 color=mag,
                                                 colorbar=True,
                                                 rescale_lengths=False,
                                                 ylabel='latitude')
コード例 #26
0
 def _hvplot_trajectory(self, traj):
     line_gdf = self._make_line_df(traj)
     if not traj.is_latlon and traj.crs is not None:
         line_gdf = line_gdf.to_crs(epsg=4326)
     if self.column and type(self.column) == str:
         self.kwargs['c'] = dim(
             self.column
         )  # fixes https://github.com/anitagraser/movingpandas/issues/71
     if self.column and self.column_to_color:
         try:
             color = self.column_to_color[traj.df[self.column].max()]
         except KeyError:
             color = 'grey'
         return line_gdf.hvplot(color=color,
                                geo=self.hvplot_is_geo,
                                tiles=self.hvplot_tiles,
                                *self.args,
                                **self.kwargs)
     else:
         return line_gdf.hvplot(geo=self.hvplot_is_geo,
                                tiles=self.hvplot_tiles,
                                *self.args,
                                **self.kwargs)
コード例 #27
0
ファイル: projects.py プロジェクト: andre-aion/analytics_demo
        def chord_diagram(self, launch):
            try:

                def normalize_value(x, total):
                    x = int((x / total) * 1000)
                    if x <= 0:
                        return 1
                    return x

                df = self.df.copy()

                # --------------  nodes
                data = {}
                data['nodes'] = []
                source_list = df['milestone_owner'].tolist()
                names = list(set(source_list))

                person_type_dict = dict(zip(df.milestone_owner, df.type))
                type_dict = {}
                types = list(set(df['type'].tolist()))
                name_dict = {}
                for idx, name in enumerate(names):
                    name_dict[name] = idx

                for idx, name in enumerate(names):
                    type_tmp = person_type_dict[name]
                    index = name_dict[name]
                    data['nodes'].append({
                        'OwnerID': index,
                        'index': idx,
                        'Type': type_tmp
                    })

                nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')

                # --------- make the links

                data['links'] = []

                for idx, row in df.iterrows():
                    src = name_dict[row['project_owner']]
                    tgt = name_dict[row['milestone_owner']]
                    val = row['remuneration']
                    data['links'].append({
                        'source': src,
                        'target': tgt,
                        'value': val
                    })

                links = pd.DataFrame(data['links'])
                # get the individual links
                links = links.groupby(['source', 'target'])['value'].sum()
                links = links.reset_index()
                total = links['value'].sum()
                links['value'] = links['value'].apply(
                    lambda x: normalize_value(x, total))

                # filter for top percentile
                quantile_val = links['value'].quantile(
                    self.chord_data['percentile_threshold'])
                links = links[links['value'] >= quantile_val]
                #logger.warning('after quantile filter:%s',len(links))

                chord_ = hv.Chord((links, nodes), ['source', 'target'],
                                  ['value'])
                chord_.opts(
                    opts.Chord(cmap='Category20',
                               edge_cmap='Category20',
                               edge_color=dim('source').str(),
                               labels='Type',
                               node_color=dim('index').str(),
                               width=1000,
                               height=1000))

                return chord_

            except Exception:
                logger.error('chord diagram', exc_info=True)
コード例 #28
0
# Specify the plot render to use
hv.extension('bokeh')
hv.output(size=300)

# Chord diagram with interactive components
edgeList = edges[['Source', 'Target', 'weight']]
# Within the holoviews dataset object we define kdim and vdims
# Kdims are the independent variables which is Id in this example
# Vdims are dependent variables cent_value and rank_value
# By defining these here were can use them when creating the graph
nodeDS = hv.Dataset(nodes_extended, 'Id', ['cent_value', 'rank_value'])

# Coloured interactive chord diagram with node size determined by Vdims
kwargs = dict(width=300, height=300, xaxis=None, yaxis=None)
opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs))

graph = hv.Graph((edgeList, nodeDS), label='GoT season 1')
graph.opts(cmap='Category20',
           edge_cmap='Category20',
           node_size='cent_value',
           edge_line_width=1,
           node_color=dim('Id').str(),
           edge_color=dim('Source').str())
graph.opts(
    opts.Chord(inspection_policy='nodes',
               tools=['hover'],
               edge_hover_line_color='green',
               node_hover_fill_color='red'))

hv.save(graph, 'node_size_chord.html')
コード例 #29
0
ファイル: flowchart.py プロジェクト: ClintonEmok/DBL-Backend
#plot = figure(title="Networkx Integration Demonstration", x_range=(-1.1,1.1), y_range=(-1.1,1.1),
              #tools="", toolbar_location=None)
#graph = hv.Graph.from_networkx(B, nx.bipartite_layout(B, nodes=l)).opts(tools=['hover'], directed=True,
                                                                           # node_size=25, inspection_policy='edges',
                                                                            #arrowhead_length=0.1)
                                                                           # , vdims='weight')
#plot.hv.render(graph)

#output_file("networkx_graph.html")
#show(plot)


renderer = hv.renderer('bokeh')
# actually drawing the graph with holoviews
flowchart = hv.Graph.from_networkx(B, nx.bipartite_layout(B, nodes=l), vdims='weight').opts(tools=['hover'], directed=True,
                                                                            node_size=25, inspection_policy='edges',
                                                                            arrowhead_length=0.1)
                                                                            #edge_line_width=B.nodes('weight'))
                                                                            #, vdims='weight')

labels = hv.Labels(flowchart.nodes, ['x', 'y'], 'index')
#layout = flowchart * labels.opts(text_font_size='8pt', text_color='red', bgcolor='white')

#doc = renderer.server_doc(layout)
show(hv.render(flowchart.opts(edge_line_width=hv.dim('weight')*3) * labels.opts(text_font_size='8pt', text_color='red',
                                                                                 bgcolor='white')))
#from bokeh.server.server import Server

#server = Server({'/': app}, port=0)
コード例 #30
0

# Set up StreamingDataFrame and add async callback

cpu_stream = hv.streams.Buffer(get_cpu_data(), 800, index=False)
mem_stream = hv.streams.Buffer(get_mem_data())


def cb():
    cpu_stream.send(get_cpu_data())
    mem_stream.send(get_mem_data())


# Define DynamicMaps and display plot

cpu_dmap = hv.DynamicMap(cpu_box, streams=[cpu_stream])
mem_dmap = hv.DynamicMap(mem_stack, streams=[mem_stream])

plot = (cpu_dmap + mem_dmap).opts(
    opts.Area(height=400, width=400, ylim=(0, 100)),
    opts.BoxWhisker(box_fill_color=dim('CPU').str(),
                    cmap='Category20',
                    width=500,
                    height=400,
                    ylim=(0, 100)))

# Render plot and attach periodic callback

doc = renderer.server_doc(plot)
doc.add_periodic_callback(cb, 0.05)
コード例 #31
0
ファイル: gapminder.py プロジェクト: basnijholt/holoviews
    'Life expectancy': dict(label='Life expectancy at birth (years)', range=(15, 100)),
    'Population': ('population', 'Population')
}

# Create Points plotting fertility vs life expectancy indexed by Year
gapminder_ds = ds.redim(**dimensions).to(hv.Points, kdims, vdims, 'Year')

# Define annotations
text = gapminder_ds.clone({yr: hv.Text(1.2, 25, str(int(yr)), fontsize=30)
                           for yr in gapminder_ds.keys()})

# Define options
# Combine Points and Text
hvgapminder = (gapminder_ds * text).opts(
    opts.Points(alpha=0.6, color='Group', cmap='Set1', line_color='black', 
                size=np.sqrt(dim('Population'))*0.005, width=1000, height=600,
                tools=['hover'], title='Gapminder Demo'),
    opts.Text(text_font_size='52pt', text_color='lightgray'))


# Define custom widgets
def animate_update():
    year = slider.value + 1
    if year > end:
        year = start
    slider.value = year

# Update the holoviews plot by calling update with the new year.
def slider_update(attrname, old, new):
    hvplot.update((new,))
コード例 #32
0
    return hv.Area.stack(areas.overlay()).relabel('Memory')

def cpu_box(data):
    return hv.BoxWhisker(data, 'CPU', 'Utilization').relabel('CPU Usage')


# Set up StreamingDataFrame and add async callback

cpu_stream = hv.streams.Buffer(get_cpu_data(), 800, index=False)
mem_stream = hv.streams.Buffer(get_mem_data())

def cb():
    cpu_stream.send(get_cpu_data())
    mem_stream.send(get_mem_data())


# Define DynamicMaps and display plot

cpu_dmap = hv.DynamicMap(cpu_box, streams=[cpu_stream])
mem_dmap = hv.DynamicMap(mem_stack, streams=[mem_stream])

plot = (cpu_dmap + mem_dmap).opts(
    opts.Area(height=400, width=400, ylim=(0, 100)),
    opts.BoxWhisker(box_fill_color=dim('CPU').str(), cmap='Category20',
                    width=500, height=400, ylim=(0, 100)))

# Render plot and attach periodic callback

doc = renderer.server_doc(plot)
doc.add_periodic_callback(cb, 0.05)