def test_stack_merge_aligned_axis():
    # If/when non_aligned axis become supported, these can be removed
    img3 = tf.Image(np.arange(4, dtype='uint32').reshape((2, 2)),
                    x_axis=x_axis, y_axis=LinearAxis((1, 20)))
    img4 = tf.Image(np.arange(9, dtype='uint32').reshape((3, 3)),
                    x_axis=x_axis, y_axis=y_axis)
    with pytest.raises(NotImplementedError):
        tf.stack(img1, img3)
    with pytest.raises(NotImplementedError):
        tf.stack(img1, img4)
    with pytest.raises(NotImplementedError):
        tf.merge(img1, img3)
    with pytest.raises(NotImplementedError):
        tf.merge(img1, img4)
Exemple #2
0
def create_map2():

    global cvs
    global terrain
    global water
    global trees

    img = stack(shade(terrain, cmap=['black', 'white'], how='linear'))

    yield img.to_pil()

    img = stack(shade(terrain, cmap=Elevation, how='linear'))

    yield img.to_pil()

    img = stack(
        shade(terrain, cmap=Elevation, how='linear'),
        shade(hillshade(terrain, azimuth=210),
              cmap=['black', 'white'],
              how='linear',
              alpha=128),
    )

    yield img.to_pil()

    img = stack(
        shade(terrain, cmap=Elevation, how='linear'),
        shade(water, cmap=['aqua', 'white']),
        shade(hillshade(terrain, azimuth=210),
              cmap=['black', 'white'],
              how='linear',
              alpha=128),
    )

    yield img.to_pil()

    img = stack(
        shade(terrain, cmap=Elevation, how='linear'),
        shade(water, cmap=['aqua', 'white']),
        shade(hillshade(terrain + trees, azimuth=210),
              cmap=['black', 'white'],
              how='linear',
              alpha=128), shade(tree_colorize, cmap='limegreen', how='linear'))

    yield img.to_pil()
    yield img.to_pil()
    yield img.to_pil()
    yield img.to_pil()
Exemple #3
0
    def _process(self, overlay, key=None):
        if not isinstance(overlay, CompositeOverlay):
            return overlay
        elif len(overlay) == 1:
            return overlay.last if isinstance(overlay, NdOverlay) else overlay.get(0)

        imgs = []
        for rgb in overlay:
            if not isinstance(rgb, RGB):
                raise TypeError('stack operation expect RGB type elements, '
                                'not %s name.' % type(rgb).__name__)
            rgb = rgb.rgb
            dims = [kd.name for kd in rgb.kdims][::-1]
            coords = {kd.name: rgb.dimension_values(kd, False)
                      for kd in rgb.kdims}
            imgs.append(tf.Image(self.uint8_to_uint32(rgb), coords=coords, dims=dims))

        try:
            imgs = xr.align(*imgs, join='exact')
        except ValueError:
            raise ValueError('RGB inputs to stack operation could not be aligned, '
                             'ensure they share the same grid sampling.')

        stacked = tf.stack(*imgs, how=self.p.compositor)
        arr = shade.uint32_to_uint8(stacked.data)[::-1]
        data = (coords[dims[1]], coords[dims[0]], arr[:, :, 0],
                arr[:, :, 1], arr[:, :, 2])
        if arr.shape[-1] == 4:
            data = data + (arr[:, :, 3],)
        return rgb.clone(data, datatype=[rgb.interface.datatype]+rgb.datatype)
Exemple #4
0
def create_image(x_range, y_range, w, h):
    cvs = ds.Canvas(x_range=x_range, y_range=y_range, plot_width=w, plot_height=h)
#    agg = cvs.points(df, 'tick', col)
    aggs = OrderedDict((c, cvs.points(df, 'tick', c)) for c in ['cpuLat', 'gpuLat'])
#    img = tf.shade(agg, cmap=[color])
    imgs = [tf.shade(aggs[i], cmap=[c]) for i,c in zip(['cpuLat', 'gpuLat'],['blue', 'red'])]
    img = tf.stack(*imgs)
    return img
def merged_images(x_range, y_range, w, h, how='log'):
    cvs = ds.Canvas(plot_width=w, plot_height=h, x_range=x_range, y_range=y_range)
    picks = cvs.points(sep_trips, 'pickup_x',  'pickup_y',  ds.count('passenger_count'))
    drops = cvs.points(sep_trips, 'dropoff_x', 'dropoff_y', ds.count('passenger_count'))
    more_drops = tf.interpolate(drops.where(drops > picks), cmap=["lightblue", 'blue'], how=how)
    more_picks = tf.interpolate(picks.where(picks > drops), cmap=["lightpink", 'red'],  how=how)
    img = tf.stack(more_picks,more_drops)
    return tf.dynspread(img, threshold=0.1, max_px=4)
Exemple #6
0
def graphplot(nodes, edges, name="", canvas=None, cat=None):
    if canvas is None:
        xr = nodes.x.min(), nodes.x.max()
        yr = nodes.y.min(), nodes.y.max()
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
        
    np = nodesplot(nodes, name + " nodes", canvas, cat)
    ep = edgesplot(edges, name + " edges", canvas)
    return tf.stack(ep, np, how="over", name=name)
def test_stack():
    img = tf.stack(img1, img2)
    assert img.x_axis == img1.x_axis and img.y_axis == img1.y_axis
    chan = img.img.view([('r', 'uint8'), ('g', 'uint8'),
                         ('b', 'uint8'), ('a', 'uint8')])
    assert (chan['r'] == np.array([[255, 0], [0, 255]])).all()
    assert (chan['g'] == np.array([[255, 0], [0, 125]])).all()
    assert (chan['b'] == np.array([[0, 0], [0, 125]])).all()
    assert (chan['a'] == np.array([[255, 0], [255, 125]])).all()
Exemple #8
0
def graphplot(nodes, edges, name="", canvas=None, cat=None):
    if canvas is None:
        xr = nodes.x.min(), nodes.x.max()
        yr = nodes.y.min(), nodes.y.max()
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)

    np = nodesplot(nodes, name + " nodes", canvas, cat)
    ep = edgesplot(edges, name + " edges", canvas)
    return tf.stack(ep, np, how="over", name=name)
Exemple #9
0
def my_graphplot(nodes, edges, name="", canvas=None, cat=None, margin=0.05):
    if canvas is None:
        xr = nodes.x.min() - margin, nodes.x.max() + margin
        yr = nodes.y.min() - margin, nodes.y.max() + margin
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
        
    np = my_nodesplot(nodes, name + " nodes", canvas, cat)
    ep = edgesplot(edges, name + " edges", canvas)
    return tf.stack(ep, np, how="over", name=name)
Exemple #10
0
def newGraphplot(nodes, edges, name="", canvas=None, cat=None, x_range=None, y_range=None):
    if canvas is None:
        xr = x_range
        yr = y_range
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
    np = nodesplot(nodes, name + " nodes", canvas, cat)
    #print("nodes")
    ep = edgesplot(edges, name + " edges", canvas)
    #print("edges")
    return tf.stack(ep, np, how="over", name=name)
Exemple #11
0
def test_stack():
    img = tf.stack(img1, img2)
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    chan = img.data.view([('r', 'uint8'), ('g', 'uint8'), ('b', 'uint8'),
                          ('a', 'uint8')])
    assert (chan['r'] == np.array([[255, 0], [0, 255]])).all()
    assert (chan['g'] == np.array([[255, 0], [0, 125]])).all()
    assert (chan['b'] == np.array([[0, 0], [0, 125]])).all()
    assert (chan['a'] == np.array([[255, 0], [255, 125]])).all()
Exemple #12
0
def newGraphplot(nodes, edges, name="", canvas=None, cat=None, x_range=None, y_range=None):
    if canvas is None:
        xr = x_range
        yr = y_range
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
    #print(x_range)
    np = nodesplot(nodes, name + " nodes", canvas, cat)
    #print(np)
    ep = edgesplot(edges, name + " edges", canvas)
    #print(ep)
    return tf.stack(ep, np, how="over", name=name)
Exemple #13
0
def graph_plot(nodes, edges, name="", canvas=None, cat=None, kwargs=cvsopts):
    '''
    Plot graph using datashader Canvas functions.
    returns datashader.transfer_functions.stack().
    '''
    if canvas is None:
        xr = nodes.x.min(), nodes.x.max()
        yr = nodes.y.min(), nodes.y.max()
        canvas = ds.Canvas(**kwargs, x_range=xr, y_range=yr)
    np = nodes_plot(nodes, name + " nodes", canvas, cat)
    ep = edges_plot(edges, name + " edges", canvas)
    return tf.stack(ep, np, how="over", name=name)
def test_stack():
    img = tf.stack(img1, img2)
    out = np.array([[0xff00ffff, 0x00000000], [0x00000000, 0xff3dbfbc]],
                   dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)

    img = tf.stack(img2, img1)
    out = np.array([[0xff00ffff, 0x00000000], [0x00000000, 0xff00ff7d]],
                   dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)

    img = tf.stack(img1, img2, how='add')
    out = np.array([[0xff00ffff, 0x00000000], [0x00000000, 0xff3d3cfa]],
                   dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)
Exemple #15
0
 def viewInteractiveImage(x_range, y_range, w, h, data_source):
     cvs = cds.Canvas(
         plot_width=w, plot_height=h, x_range=x_range, y_range=y_range
     )
     aggs = dict(
         (_y, cvs.line(data_source, x=self.x, y=_y)) for _y in self.y
     )
     imgs = [
         tf.shade(aggs[_y], cmap=["white", color])
         for _y, color in zip(self.y, self.colors)
     ]
     return tf.stack(*imgs)
def test_stack():
    img = tf.stack(img1, img2)
    out = np.array([[0xff00ffff, 0x00000000],
                    [0x00000000, 0xff3dbfbc]], dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)

    img = tf.stack(img2, img1)
    out = np.array([[0xff00ffff, 0x00000000],
                    [0x00000000, 0xff00ff7d]], dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)

    img = tf.stack(img1, img2, how='add')
    out = np.array([[0xff00ffff, 0x00000000],
                    [0x00000000, 0xff3dfffa]], dtype='uint32')
    assert (img.x_axis == img1.x_axis).all()
    assert (img.y_axis == img1.y_axis).all()
    np.testing.assert_equal(img.data, out)
Exemple #17
0
def create_map(azimuth):

    global cvs
    global terrain
    global water
    global trees

    img = stack(
        shade(terrain, cmap=Elevation, how='linear'),
        shade(water, cmap=['aqua', 'white']),
        shade(hillshade(terrain + trees, azimuth=azimuth),
              cmap=['black', 'white'],
              how='linear',
              alpha=128), shade(tree_colorize, cmap='limegreen', how='linear'))

    print('image created')

    return img.to_pil()
Exemple #18
0
        def viewInteractiveImage(
            x_range,
            y_range,
            w,
            h,
            data_source=self.nodes,
            nodes_plot=self.nodes_plot,
            edges_plot=self.edges_plot,
            chart=self.chart,
            **kwargs,
        ):
            dd = data_source[[
                self.node_id,
                self.node_x,
                self.node_y,
                self.node_aggregate_col,
            ]]
            dd[self.node_x] = self._to_xaxis_type(dd[self.node_x])
            dd[self.node_y] = self._to_yaxis_type(dd[self.node_y])

            x_range = self._to_xaxis_type(x_range)
            y_range = self._to_yaxis_type(y_range)

            cvs = ds.Canvas(plot_width=w,
                            plot_height=h,
                            x_range=x_range,
                            y_range=y_range)
            plot = None
            if self.source is not None:
                self.source.data = {
                    self.node_x: [],
                    self.node_y: [],
                    self.node_aggregate_col: [],
                    self.node_aggregate_col + "_color": [],
                }
            np = nodes_plot(cvs, dd)
            if self.display_edges._active:
                ep = edges_plot(cvs, dd)
                plot = tf.stack(ep, np, how="over")
            else:
                plot = np

            return plot
Exemple #19
0
def newGraphplot(nodes,
                 edges,
                 name="",
                 canvas=None,
                 cat=None,
                 x_range=None,
                 y_range=None):
    if canvas is None:
        xr = x_range
        yr = y_range
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
    #print(x_range)
    np = nodesplot(nodes, name + " nodes", canvas, cat)
    print('Nodes plot created', file=sys.stdout)
    #print(np)
    #issue is here with edges
    ep = edgesplot(edges, name + " edges", canvas)
    print('Edges plot created', file=sys.stdout)
    #print(ep)
    return tf.stack(ep, np, how="over", name=name)
Exemple #20
0
        def viewInteractiveImage(x_range, y_range, w, h, data_source,
                                 **kwargs):
            dd = data_source[[self.x] + self.y]
            dd[self.x] = self._to_xaxis_type(dd[self.x])
            for _y in self.y:
                dd[_y] = self._to_yaxis_type(dd[_y])

            x_range = self._to_xaxis_type(x_range)
            y_range = self._to_yaxis_type(y_range)

            cvs = ds.Canvas(plot_width=w,
                            plot_height=h,
                            x_range=x_range,
                            y_range=y_range)
            aggs = dict((_y, cvs.line(dd, x=self.x, y=_y)) for _y in self.y)
            imgs = [
                tf.shade(aggs[_y], cmap=["white", color])
                for _y, color in zip(self.y, self.colors)
            ]
            return tf.stack(*imgs)
def create_plot(data, out, width):
    """Creates a figure of the ZVV transit network using ZVV's color scheme.

    Args:
        data: a csv file containing data usable for line plots
        out: the generated imnage is saved here

    Returns:
        None
    """

    plot_data = pd.read_csv(data, low_memory=False)

    x_range = (plot_data.shape_pt_lon.min(), plot_data.shape_pt_lon.max())
    y_range = (plot_data.shape_pt_lat.min(), plot_data.shape_pt_lat.max())

    height = int(
        round(width * (y_range[1] - y_range[0]) / (x_range[1] - x_range[0])))

    cvs = ds.Canvas(plot_width=width,
                    plot_height=height,
                    x_range=x_range,
                    y_range=y_range)

    layers = []
    for color, data_part in plot_data.groupby('route_color'):
        agg = cvs.line(data_part,
                       'shape_pt_lon',
                       'shape_pt_lat',
                       agg=ds.sum('times_taken'))
        image_part = tf.shade(agg,
                              cmap=['#000000', '#' + color],
                              how='eq_hist')
        layers.append(image_part)

    image = tf.stack(*layers, how='add')

    if out.endswith('.png'):
        out = out[:-4]
    export_image(image, filename=out, background='black')
Exemple #22
0
def connectivity_base(
    x: int,
    y: int,
    edge_df: pd.DataFrame,
    highlights: Optional[list] = None,
    edge_bundling: Optional[str] = None,
    edge_cmap: str = "gray_r",
    show_points: bool = True,
    labels: Optional[list] = None,
    values: Optional[list] = None,
    theme: Optional[str] = None,
    cmap: str = "Blues",
    color_key: Union[dict, list, None] = None,
    color_key_cmap: str = "Spectral",
    background: str = "black",
    figsize: tuple = (7, 5),
    ax: Optional[Axes] = None,
    sort: str = "raw",
    save_show_or_return: str = "return",
    save_kwargs: dict = {},
) -> Union[None, Axes]:
    """Plot connectivity relationships of the underlying UMAP
    simplicial set data structure. Internally UMAP will make
    use of what can be viewed as a weighted graph. This graph
    can be plotted using the layout provided by UMAP as a
    potential diagnostic view of the embedding. Currently this only works
    for 2D embeddings. While there are many optional parameters
    to further control and tailor the plotting, you need only
    pass in the trained/fit umap model to get results. This plot
    utility will attempt to do the hard work of avoiding
    overplotting issues and provide options for plotting the
    points as well as using edge bundling for graph visualization.

    Parameters
    ----------
        x: `int`
            The first component of the embedding.
        y: `int`
            The second component of the embedding.
        edge_df `pd.DataFrame`
            The dataframe denotes the graph edge pairs. The three columns
            include 'source', 'target' and 'weight'.
        highlights: `list`, `list of list` or None (default: `None`)
            The list that cells will be restricted to.
        edge_bundling: string or None (optional, default None)
            The edge bundling method to use. Currently supported
            are None or 'hammer'. See the datashader docs
            on graph visualization for more details.
        edge_cmap: string (default 'gray_r')
            The name of a matplotlib colormap to use for shading/
            coloring the edges of the connectivity graph. Note that
            the ``theme``, if specified, will override this.
        show_points: bool (optional False)
            Whether to display the points over top of the edge
            connectivity. Further options allow for coloring/
            shading the points accordingly.
        labels: array, shape (n_samples,) (optional, default None)
            An array of labels (assumed integer or categorical),
            one for each data sample.
            This will be used for coloring the points in
            the plot according to their label. Note that
            this option is mutually exclusive to the ``values``
            option.
        values: array, shape (n_samples,) (optional, default None)
            An array of values (assumed float or continuous),
            one for each sample.
            This will be used for coloring the points in
            the plot according to a colorscale associated
            to the total range of values. Note that this
            option is mutually exclusive to the ``labels``
            option.
        theme: string (optional, default None)
            A color theme to use for plotting. A small set of
            predefined themes are provided which have relatively
            good aesthetics. Available themes are:
               * 'blue'
               * 'red'
               * 'green'
               * 'inferno'
               * 'fire'
               * 'viridis'
               * 'darkblue'
               * 'darkred'
               * 'darkgreen'
        cmap: string (optional, default 'Blues')
            The name of a matplotlib colormap to use for coloring
            or shading points. If no labels or values are passed
            this will be used for shading points according to
            density (largely only of relevance for very large
            datasets). If values are passed this will be used for
            shading according the value. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        color_key: dict or array, shape (n_categories) (optional, default None)
            A way to assign colors to categoricals. This can either be
            an explicit dict mapping labels to colors (as strings of form
            '#RRGGBB'), or an array like object providing one color for
            each distinct category being provided in ``labels``. Either
            way this mapping will be used to color points according to
            the label. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        color_key_cmap: string (optional, default 'Spectral')
            The name of a matplotlib colormap to use for categorical coloring.
            If an explicit ``color_key`` is not given a color mapping for
            categories can be generated from the label list and selecting
            a matching list of colors from the given colormap. Note
            that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        background: string (optional, default 'white)
            The color of the background. Usually this will be either
            'white' or 'black', but any color name will work. Ideally
            one wants to match this appropriately to the colors being
            used for points etc. This is one of the things that themes
            handle for you. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        width: int (optional, default 800)
            The desired width of the plot in pixels.
        height: int (optional, default 800)
            The desired height of the plot in pixels
        sort: `str` (optional, default `raw`)
            The method to reorder data so that high values points will be on top of background points. Can be one of
            {'raw', 'abs'}, i.e. sorted by raw data or sort by absolute values.
        save_show_or_return: {'show', 'save', 'return'} (default: `return`)
            Whether to save, show or return the figure.
        save_kwargs: `dict` (default: `{}`)
            A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
            will use the {"path": None, "prefix": 'connectivity_base', "dpi": None, "ext": 'pdf', "transparent": True, "close":
            True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
            according to your needs.

    Returns
    -------
    result:
        Either return None or a matplotlib axis with the relevant plot displayed based on arguments.
        If you are using a notbooks and have ``%matplotlib inline`` set
        then this will simply display inline.
    """

    import matplotlib.pyplot as plt
    import datashader as ds
    import datashader.transfer_functions as tf
    import datashader.bundling as bd

    dpi = plt.rcParams["figure.dpi"]

    if theme is not None:
        cmap = _themes[theme]["cmap"]
        color_key_cmap = _themes[theme]["color_key_cmap"]
        edge_cmap = _themes[theme]["edge_cmap"]
        background = _themes[theme]["background"]

    points = np.array([x, y]).T
    point_df = pd.DataFrame(points, columns=("x", "y"))

    point_size = 500.0 / np.sqrt(points.shape[0])
    if point_size > 1:
        px_size = int(np.round(point_size))
    else:
        px_size = 1

    if show_points:
        edge_how = "log"
    else:
        edge_how = "eq_hist"

    extent = _get_extent(points)
    canvas = ds.Canvas(
        plot_width=int(figsize[0] * dpi),
        plot_height=int(figsize[1] * dpi),
        x_range=(extent[0], extent[1]),
        y_range=(extent[2], extent[3]),
    )

    if edge_bundling is None:
        edges = bd.directly_connect_edges(point_df, edge_df, weight="weight")
    elif edge_bundling == "hammer":
        warn("Hammer edge bundling is expensive for large graphs!\n"
             "This may take a long time to compute!")
        edges = bd.hammer_bundle(point_df, edge_df, weight="weight")
    else:
        raise ValueError(
            "{} is not a recognised bundling method".format(edge_bundling))

    edge_img = tf.shade(
        canvas.line(edges, "x", "y", agg=ds.sum("weight")),
        cmap=plt.get_cmap(edge_cmap),
        how=edge_how,
    )
    edge_img = tf.set_background(edge_img, background)

    if show_points:
        point_img = _datashade_points(
            points,
            None,
            labels,
            values,
            highlights,
            cmap,
            color_key,
            color_key_cmap,
            None,
            figsize[0] * dpi,
            figsize[1] * dpi,
            True,
            sort=sort,
        )
        if px_size > 1:
            point_img = tf.dynspread(point_img, threshold=0.5, max_px=px_size)
        result = tf.stack(edge_img, point_img, how="over")
    else:
        result = edge_img

    if ax is None:
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111)

    _embed_datashader_in_an_axis(result, ax)

    ax.set(xticks=[], yticks=[])

    if save_show_or_return == "save":
        s_kwargs = {
            "path": None,
            "prefix": "connectivity_base",
            "dpi": None,
            "ext": "pdf",
            "transparent": True,
            "close": True,
            "verbose": True,
        }
        s_kwargs = update_dict(s_kwargs, save_kwargs)

        save_fig(**s_kwargs)
    elif save_show_or_return == "show":
        plt.tight_layout()
        plt.show()
    elif save_show_or_return == "return":
        return ax
Exemple #23
0
                                  bkg=reductions.mean('Background'))

canvas = datashader.Canvas(plot_width=x_end - x_start,
                           plot_height=y_end - y_start,
                           x_range=[x_start, x_end],
                           y_range=[y_start, y_end])

agg = canvas.points(data, 'x', 'y', agg=reduction_op)

imgs = []
for morph, color in [(agg.sph, 'red'), (agg.dk, 'green'), (agg.ps, 'blue'),
                     (agg.bkg, 'black')]:
    imgs.append(
        t_func.shade(morph, cmap=['white', color], span=[0, 1], how='linear'))

img = t_func.stack(*imgs, how='add')
#img = t_func.set_background(img, color='black')

img_plt = f.image_rgba(image=[img.data],
                       x=x_start,
                       y=y_start,
                       dw=width,
                       dh=height)

outputs.append(f)

# ==============================================================================

# ==============================================================================
# plot in-segmap PDFs
pdf_cdf = []
Exemple #24
0
img = tf.shade(aggs['a'])


img

mask = (df.index % 10) == 0
tf.shade(cvs.line(df[mask][['a','ITime']], 'ITime', 'a'))

renamed = [aggs[key].rename({key: 'value'}) for key in aggs]
merged = xr.concat(renamed, 'cols')
tf.shade(merged.any(dim='cols'))

colors = ["red", "grey", "black", "purple", "pink",
          "yellow", "brown", "green", "orange", "blue"]
imgs = [tf.shade(aggs[i], cmap=[c]) for i, c in zip(cols, colors)]
tf.stack(*imgs)

tf.stack(*reversed(imgs))

total = tf.shade(merged.sum(dim='cols'), how='linear')
total

tf.stack(total, tf.shade(aggs['z'], cmap=["lightblue", "red"]))

tf.stack(total, tf.shade(aggs['y'], cmap=["lightblue", "red"]))


cvs = ds.Canvas(x_range=x_range, y_range=y_range, plot_height=300, plot_width=900)
agg = cvs.area(df, x='ITime', y='a')
img = tf.shade(agg)
img
Exemple #25
0
def shade_line(data, colors=None, **kwargs):
    """"""

    if "plot_width" not in kwargs or "plot_height" not in kwargs:
        raise ValueError(
            "Please provide plot_width and plot_height for the canvas.")

    if isinstance(data, (list, tuple)) and isinstance(colors, (list, tuple)):
        if len(data) != len(colors):
            raise ValueError("colors should have the same length as data.")

    if isinstance(data, (dict, pd.DataFrame)):
        data = [data]
    if colors and isinstance(colors, str):
        colors = [colors] * len(data)

    if "x_range" not in kwargs or "y_range" not in kwargs:
        x_range, y_range = get_ranges(data)
        if "x_range" not in kwargs:
            kwargs["x_range"] = x_range
        if "y_range" not in kwargs:
            kwargs["y_range"] = y_range

    kwargs["x_range"], kwargs["y_range"] = _normalize_ranges(
        kwargs["x_range"], kwargs["y_range"])

    cvs = ds.Canvas(**kwargs)
    aggs = []
    cs = []

    for i, line in enumerate(data):
        df = line
        if not isinstance(line, pd.DataFrame):
            df = pd.DataFrame(line).astype(float)

        plot = True
        if "x_range" in kwargs and "y_range" in kwargs:
            plot = _is_data_in_range(df, "x", "y", kwargs["x_range"],
                                     kwargs["y_range"])
        elif "x_range" in kwargs:
            plot = _is_data_in_range(df, "x", "y", kwargs["x_range"])
        elif "y_range" in kwargs:
            plot = _is_data_in_range(df, "x", "y", y_range=kwargs["y_range"])

        if len(df["x"]) == 0 or len(df["y"]) == 0:
            plot = False

        if plot:
            aggs.append(cvs.line(df, "x", "y"))
            if colors:
                cs.append(colors[i])

    if not aggs:
        return xr.DataArray(
            np.zeros((kwargs["plot_height"], kwargs["plot_width"]), dtype=int))
    if colors:
        imgs = [tf.shade(aggs[i], cmap=[c]) for i, c in enumerate(cs)]
        return tf.stack(*imgs)
    else:
        imgs = [tf.shade(aggs[i]) for i in range(len(data))]
        return tf.stack(*imgs)
Exemple #26
0
def connectivity(
    umap_object,
    edge_bundling=None,
    edge_cmap="gray_r",
    show_points=False,
    labels=None,
    values=None,
    theme=None,
    cmap="Blues",
    color_key=None,
    color_key_cmap="Spectral",
    background="white",
    width=800,
    height=800,
):
    """Plot connectivity relationships of the underlying UMAP
    simplicial set data structure. Internally UMAP will make
    use of what can be viewed as a weighted graph. This graph
    can be plotted using the layout provided by UMAP as a
    potential diagnostic view of the embedding. Currently this only works
    for 2D embeddings. While there are many optional parameters
    to further control and tailor the plotting, you need only
    pass in the trained/fit umap model to get results. This plot
    utility will attempt to do the hard work of avoiding
    overplotting issues and provide options for plotting the
    points as well as using edge bundling for graph visualization.

    Parameters
    ----------
    umap_object: trained UMAP object
        A trained UMAP object that has a 2D embedding.

    edge_bundling: string or None (optional, default None)
        The edge bundling method to use. Currently supported
        are None or 'hammer'. See the datashader docs
        on graph visualization for more details.

    edge_cmap: string (default 'gray_r')
        The name of a matplotlib colormap to use for shading/
        coloring the edges of the connectivity graph. Note that
        the ``theme``, if specified, will override this.

    show_points: bool (optional False)
        Whether to display the points over top of the edge
        connectivity. Further options allow for coloring/
        shading the points accordingly.

    labels: array, shape (n_samples,) (optional, default None)
        An array of labels (assumed integer or categorical),
        one for each data sample.
        This will be used for coloring the points in
        the plot according to their label. Note that
        this option is mutually exclusive to the ``values``
        option.

    values: array, shape (n_samples,) (optional, default None)
        An array of values (assumed float or continuous),
        one for each sample.
        This will be used for coloring the points in
        the plot according to a colorscale associated
        to the total range of values. Note that this
        option is mutually exclusive to the ``labels``
        option.

    theme: string (optional, default None)
        A color theme to use for plotting. A small set of
        predefined themes are provided which have relatively
        good aesthetics. Available themes are:
           * 'blue'
           * 'red'
           * 'green'
           * 'inferno'
           * 'fire'
           * 'viridis'
           * 'darkblue'
           * 'darkred'
           * 'darkgreen'

    cmap: string (optional, default 'Blues')
        The name of a matplotlib colormap to use for coloring
        or shading points. If no labels or values are passed
        this will be used for shading points according to
        density (largely only of relevance for very large
        datasets). If values are passed this will be used for
        shading according the value. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    color_key: dict or array, shape (n_categories) (optional, default None)
        A way to assign colors to categoricals. This can either be
        an explicit dict mapping labels to colors (as strings of form
        '#RRGGBB'), or an array like object providing one color for
        each distinct category being provided in ``labels``. Either
        way this mapping will be used to color points according to
        the label. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    color_key_cmap: string (optional, default 'Spectral')
        The name of a matplotlib colormap to use for categorical coloring.
        If an explicit ``color_key`` is not given a color mapping for
        categories can be generated from the label list and selecting
        a matching list of colors from the given colormap. Note
        that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    background: string (optional, default 'white)
        The color of the background. Usually this will be either
        'white' or 'black', but any color name will work. Ideally
        one wants to match this appropriately to the colors being
        used for points etc. This is one of the things that themes
        handle for you. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    width: int (optional, default 800)
        The desired width of the plot in pixels.

    height: int (optional, default 800)
        The desired height of the plot in pixels

    Returns
    -------
    result: matplotlib axis
        The result is a matplotlib axis with the relevant plot displayed.
        If you are using a notbooks and have ``%matplotlib inline`` set
        then this will simply display inline.
    """
    if theme is not None:
        cmap = _themes[theme]["cmap"]
        color_key_cmap = _themes[theme]["color_key_cmap"]
        edge_cmap = _themes[theme]["edge_cmap"]
        background = _themes[theme]["background"]

    points = umap_object.embedding_
    point_df = pd.DataFrame(points, columns=("x", "y"))

    point_size = 100.0 / np.sqrt(points.shape[0])
    if point_size > 1:
        px_size = int(np.round(point_size))
    else:
        px_size = 1

    if show_points:
        edge_how = "log"
    else:
        edge_how = "eq_hist"

    coo_graph = umap_object.graph_.tocoo()
    edge_df = pd.DataFrame(
        np.vstack([coo_graph.row, coo_graph.col, coo_graph.data]).T,
        columns=("source", "target", "weight"),
    )
    edge_df["source"] = edge_df.source.astype(np.int32)
    edge_df["target"] = edge_df.target.astype(np.int32)

    extent = _get_extent(points)
    canvas = ds.Canvas(
        plot_width=width,
        plot_height=height,
        x_range=(extent[0], extent[1]),
        y_range=(extent[2], extent[3]),
    )

    if edge_bundling is None:
        edges = bd.directly_connect_edges(point_df, edge_df, weight="weight")
    elif edge_bundling == "hammer":
        warn("Hammer edge bundling is expensive for large graphs!\n"
             "This may take a long time to compute!")
        edges = bd.hammer_bundle(point_df, edge_df, weight="weight")
    else:
        raise ValueError(
            "{} is not a recognised bundling method".format(edge_bundling))

    edge_img = tf.shade(
        canvas.line(edges, "x", "y", agg=ds.sum("weight")),
        cmap=plt.get_cmap(edge_cmap),
        how=edge_how,
    )
    edge_img = tf.set_background(edge_img, background)

    if show_points:
        point_img = _datashade_points(
            points,
            None,
            labels,
            values,
            cmap,
            color_key,
            color_key_cmap,
            None,
            width,
            height,
            False,
        )
        if px_size > 1:
            point_img = tf.dynspread(point_img, threshold=0.5, max_px=px_size)
        result = tf.stack(edge_img, point_img, how="over")
    else:
        result = edge_img

    font_color = _select_font_color(background)

    dpi = plt.rcParams["figure.dpi"]
    fig = plt.figure(figsize=(width / dpi, height / dpi))
    ax = fig.add_subplot(111)

    _embed_datashader_in_an_axis(result, ax)

    ax.set(xticks=[], yticks=[])
    ax.text(
        0.99,
        0.01,
        "UMAP: n_neighbors={}, min_dist={}".format(umap_object.n_neighbors,
                                                   umap_object.min_dist),
        transform=ax.transAxes,
        horizontalalignment="right",
        color=font_color,
    )

    return ax