Python matplotlib.pyplot.Normalize() Examples

The following are 30 code examples of matplotlib.pyplot.Normalize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_Normalize():
    norm = mcolors.Normalize()
    vals = np.arange(-10, 10, 1, dtype=float)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Handle integer input correctly (don't overflow when computing max-min,
    # i.e. 127-(-128) here).
    vals = np.array([-128, 127], dtype=np.int8)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])

    # Don't lose precision on longdoubles (float128 on Linux):
    # for array inputs...
    vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])
    # and for scalar ones.
    eps = np.finfo(np.longdouble).resolution
    norm = plt.Normalize(1, 1 + 100 * eps)
    # This returns exactly 0.5 when longdouble is extended precision (80-bit),
    # but only a value close to it when it is quadruple precision (128-bit).
    assert 0 < norm(1 + 50 * eps) < 1 
Example #2
Source File: plot.py    From deephar with MIT License 6 votes vote down vote up
def show(x, gray_scale=False, jet_cmap=False, filename=None):
    """ Show 'x' as an image on the screen.
    """
    if jet_cmap is False:
        img = data_to_image(x, gray_scale=gray_scale)
    else:
        if plt is None:
            printcn(WARNING, 'pyplot not defined!')
            return
        cmap = plt.cm.jet
        norm = plt.Normalize(vmin=x.min(), vmax=x.max())
        img = cmap(norm(x))
    if filename:
        plt.imsave(filename, img)
    else:
        plt.imshow(img)
        plt.show() 
Example #3
Source File: webcan.py    From pose-regression with MIT License 6 votes vote down vote up
def draw_heatmaps(screen, surf, hm, thr=0.5, vmin=-15, vmax=10):
    hm_idx = [
            ( 8, 0*hmsurf_size[0], 0*hmsurf_size[1]),   # R. wrist
            ( 9, 1*hmsurf_size[0], 0*hmsurf_size[1]),   # L. wrist
            ( 6, 0*hmsurf_size[0], 1*hmsurf_size[1]),   # R. elbow
            ( 7, 1*hmsurf_size[0], 1*hmsurf_size[1]),   # L. elbow
            ( 3, 0*hmsurf_size[0], 2*hmsurf_size[1]),   # Head
            ( 0, 1*hmsurf_size[0], 2*hmsurf_size[1]),   # Pelvis
            (12, 0*hmsurf_size[0], 3*hmsurf_size[1]),   # R. knee
            (13, 1*hmsurf_size[0], 3*hmsurf_size[1])]   # L. knee

    for idx in hm_idx:
        h = np.transpose(hm[:,:,idx[0]].copy(), (1, 0))
        h[h < vmin] = vmin
        h[h > vmax] = vmax
        cmap = plt.cm.jet
        norm = plt.Normalize(vmin=vmin, vmax=vmax)
        cm = np.zeros((34, 34, 3))
        cm[1:33, 1:33, :] = cmap(norm(h))[:,:,0:3]
        cm = scipy.ndimage.zoom(cm, (5, 5, 1), order=1)
        pygame.surfarray.pixels3d(surf)[:,:,:] = np.array(255.*cm, dtype=int)
        screen.blit(surf, (idx[1] + img_size[0], idx[2])) 
Example #4
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_Normalize():
    norm = mcolors.Normalize()
    vals = np.arange(-10, 10, 1, dtype=float)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Handle integer input correctly (don't overflow when computing max-min,
    # i.e. 127-(-128) here).
    vals = np.array([-128, 127], dtype=np.int8)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])

    # Don't lose precision on longdoubles (float128 on Linux):
    # for array inputs...
    vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])
    # and for scalar ones.
    eps = np.finfo(np.longdouble).resolution
    norm = plt.Normalize(1, 1 + 100 * eps)
    # This returns exactly 0.5 when longdouble is extended precision (80-bit),
    # but only a value close to it when it is quadruple precision (128-bit).
    assert 0 < norm(1 + 50 * eps) < 1 
Example #5
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_Normalize():
    norm = mcolors.Normalize()
    vals = np.arange(-10, 10, 1, dtype=float)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Handle integer input correctly (don't overflow when computing max-min,
    # i.e. 127-(-128) here).
    vals = np.array([-128, 127], dtype=np.int8)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])

    # Don't lose precision on longdoubles (float128 on Linux):
    # for array inputs...
    vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])
    # and for scalar ones.
    eps = np.finfo(np.longdouble).resolution
    norm = plt.Normalize(1, 1 + 100 * eps)
    # This returns exactly 0.5 when longdouble is extended precision (80-bit),
    # but only a value close to it when it is quadruple precision (128-bit).
    assert 0 < norm(1 + 50 * eps) < 1 
Example #6
Source File: axes.py    From phoebe2 with GNU General Public License v3.0 6 votes vote down vote up
def get_norm(self, pad=None, i=None):
        """
        Compute the adopted normalization at a given value of `i`, given the
        value of <autofig.axes.AxDimension.pad> (or `pad`).

        See also:

        * <autofig.axes.AxDimension.norm>

        Arguments
        -----------
        * `pad` (float, optional, default=None): override the padding.  If not
            provided or None, will use <autofig.axes.AxDimension.pad>.
        * `i` (float, optional, default=None): the value to use for `i` when
            computing visible data and limits.

        Returns
        --------
        * (plt.Normalize object)
        """
        return plt.Normalize(*self.get_lim(pad=pad, i=i)) 
Example #7
Source File: call.py    From phoebe2 with GNU General Public License v3.0 6 votes vote down vote up
def get_sizes(self, i=None):

        s = self.s.get_value(i=i, unit=self.axes_s.unit if self.axes_s is not None else None)

        if self.do_sizescale:
            if self.axes_s is not None:
                sizes = self.axes_s.normalize(s, i=i)
            else:
                # fallback on 0.01-0.05 mapping for just this call
                sall = self.s.get_value(unit=self.axes_s.unit if self.axes_s is not None else None)
                norm = plt.Normalize(np.nanmin(sall), np.nanmax(sall))
                sizes = norm(s) * 0.04+0.01

        else:
            if s is not None:
                sizes = s
            elif self.s.mode == 'pt':
                sizes = 1
            else:
                sizes = 0.02

        return sizes 
Example #8
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_LogNorm():
    """
    LogNorm ignored clip, now it has the same
    behavior as Normalize, e.g., values > vmax are bigger than 1
    without clip, with clip they are 1.
    """
    ln = mcolors.LogNorm(clip=True, vmax=5)
    assert_array_equal(ln([1, 6]), [0, 1.0]) 
Example #9
Source File: CPOETrackerAnalysis.py    From CDSS with GNU General Public License v3.0 5 votes vote down vote up
def visualize_timeline(self, timeline):
		"""Draw timeline

		Args:
			timeline (iterable): iterable of tuples (position, name, info_dict)
		"""
		times = list([datetime.datetime.fromtimestamp((x[0] - timeline[0][0])/1000.0) for x in timeline])
		names = list([x[1] for x in timeline])
		names_unique = sorted(list(set(list([x for x in names]))))


		norm = plt.Normalize(1,4)
		c = np.random.randint(1,5,size=len(names_unique))
		cmap = plt.cm.inferno
		fig, ax = plt.subplots(figsize=(15,4))

		ax.yaxis.set_visible(False)
		ax.spines['right'].set_visible(False)
		ax.spines['left'].set_visible(False)
		ax.spines['top'].set_visible(False)
		ax.xaxis.set_ticks_position('bottom')

		ax.get_yaxis().set_ticklabels([])
		ms = pd.to_timedelta("1", unit='ms')
		plt.xlim(times[0] - 5*ms, times[-1] + 5*ms)

		plots = []

		for i, name in enumerate(names_unique):
			named_events = list([x for x in timeline if x[1] == name])
			named_times = list([datetime.datetime.fromtimestamp((x[0] - timeline[0][0])/1000.0) for x in named_events])
			sc = plt.scatter(named_times, [i*5+1]*len(named_times), marker='o', s=100, alpha=0.8)
			plots.append(sc)

		ax.legend(plots, names_unique)
		plt.show() 
Example #10
Source File: CPOETrackerAnalysis.py    From CDSS with GNU General Public License v3.0 5 votes vote down vote up
def visualize_timeline(self, timeline):
		"""Draw timeline
		Args:
			timeline (iterable): iterable of tuples (position, name, info_dict)
		"""
		times = list([datetime.datetime.fromtimestamp((x[0] - timeline[0][0])/1000.0) for x in timeline])
		names = list([x[1] for x in timeline])
		names_unique = sorted(list(set(list([x for x in names]))))


		norm = plt.Normalize(1,4)
		c = np.random.randint(1,5,size=len(names_unique))
		cmap = plt.cm.inferno
		fig, ax = plt.subplots(figsize=(15,4))

		ax.yaxis.set_visible(False)
		ax.spines['right'].set_visible(False)
		ax.spines['left'].set_visible(False)
		ax.spines['top'].set_visible(False)
		ax.xaxis.set_ticks_position('bottom')

		ax.get_yaxis().set_ticklabels([])
		ms = pd.to_timedelta("1", unit='ms')
		plt.xlim(times[0] - 5*ms, times[-1] + 5*ms)

		plots = []

		for i, name in enumerate(names_unique):
			named_events = list([x for x in timeline if x[1] == name])
			named_times = list([datetime.datetime.fromtimestamp((x[0] - timeline[0][0])/1000.0) for x in named_events])
			sc = plt.scatter(named_times, [i*5+1]*len(named_times), marker='o', s=100, alpha=0.8)
			plots.append(sc)

		ax.legend(plots, names_unique)
		plt.show() 
Example #11
Source File: PlotClass.py    From ldgcnn with MIT License 5 votes vote down vote up
def plot_points_with_color(points,label,face_id, fig, axis_off = False):
        ax = fig.add_subplot(111, projection='3d')
        norm = plt.Normalize()
        colors = plt.cm.hsv(norm(face_id))
        ax.scatter(points[:,0], points[:,1], points[:,2], c = colors)
        ax.view_init(elev=0, azim=90)
        fontsize = 20
        if axis_off:
            ax.set_axis_off()
        else:
            ax.set_xlabel('x', fontsize=fontsize)
            ax.set_ylabel('y', fontsize=fontsize)
            ax.set_title(label, fontsize=fontsize)
        fig.subplots_adjust(left=0, right=1, bottom=0, top=1,wspace = 0, hspace = 0)
        plt.show() 
Example #12
Source File: axes.py    From phoebe2 with GNU General Public License v3.0 5 votes vote down vote up
def norm(self):
        """
        Compute the adopted normalization with `i=None` and the value of
        <autofig.axes.AxDimension.pad>.

        See also:

        * <autofig.axes.AxDimension.get_norm>

        Returns
        -----------
        * (plt.Normalize object)
        """
        return self.get_norm(pad=self.pad) 
Example #13
Source File: complexity_embedding.py    From NeuroKit with MIT License 5 votes vote down vote up
def _plot_3D_colored(x, y, z, color=None, rotate=False):
    if color is None:
        color = z

    # Create a set of line segments
    points = np.array([x, y, z]).T.reshape(-1, 1, 3)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    # Color
    norm = plt.Normalize(color.min(), color.max())
    cmap = plt.get_cmap("plasma")
    colors = cmap(norm(color))

    # Plot
    fig = plt.figure()
    ax = fig.gca(projection="3d")

    for i in range(len(x) - 1):
        seg = segments[i]
        (l,) = ax.plot(seg[:, 0], seg[:, 1], seg[:, 2], color=colors[i])
        l.set_solid_capstyle("round")

    if rotate is True:
        fig = _plot_3D_colored_rotate(fig, ax)

    return fig 
Example #14
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #15
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        assert len(recwarn) == 0
        recwarn.clear() 
Example #16
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_LogNorm():
    """
    LogNorm ignored clip, now it has the same
    behavior as Normalize, e.g., values > vmax are bigger than 1
    without clip, with clip they are 1.
    """
    ln = mcolors.LogNorm(clip=True, vmax=5)
    assert_array_equal(ln([1, 6]), [0, 1.0]) 
Example #17
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #18
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        if isinstance(norm, mcolors.PowerNorm):
            assert len(recwarn) == 1
            warn = recwarn.pop(UserWarning)
            assert ('Power-law scaling on negative values is ill-defined'
                    in str(warn.message))
        else:
            assert len(recwarn) == 0
        recwarn.clear() 
Example #19
Source File: utils.py    From meshplot with GNU General Public License v3.0 5 votes vote down vote up
def get_colors(inp, colormap="viridis", normalize=True, vmin=None, vmax=None):
    colormap = plt.cm.get_cmap(colormap)
    if normalize:
        vmin=np.min(inp)
        vmax=np.max(inp)

    norm = plt.Normalize(vmin, vmax)
    return colormap(norm(inp))[:, :3] 
Example #20
Source File: colormap2d.py    From ocelot with GNU General Public License v3.0 5 votes vote down vote up
def imshow2d(data, ax=None, cmap2d='brightwheel', huenorm=None, huevmin=None,
             huevmax=None, lightnorm=None, lightvmin=None, lightvmax=None,
             **kwargs):
    """
    Plot 2 parameter 2D data array to current axis.

    :param data: numpy array with shape (2, nwidth, nheight). The first index
                 corresponds to the hue and the second to the lightness of the
                 colors.
    :param ax: a matplotlib axis instance.
    :param cmap: either:
                 numpy array with shape (nwidth, nheight, 4) that contains
                 the 4 rgba values in hue (width) and lightness (height).
                 Can be obtained by a call to get_cmap2d(name).
                 or:
                 name where name is one of the following strings:
                 'brightwheel', 'darkwheel', 'hardwheel', 'newwheel',
                 'smoothwheel', 'wheel'
    :param huenorm: a plt.Normalize() instance that normalizes the hue values.
    :param huevmin: the minimum of the huevalues. Only used if huenorm=None.
    :param huevmax: the maximum of the huevalues. Only used if huenorm=None.
    :param lightnorm: a plt.Normalize() instance that normalizes the lightness
                      values.
    :param lightvmin: the minimum of the lightness values.
                      Only used if lightnorm=None.
    :param lightvmax: the maximum of the lightness values.
                      Only used if lightnorm=None.
    :param **kwargs: remaining kwargs are passed to plt.imshow()
    """
    if ax is None:
        ax = plt.gca()
    rgb_data = data2d_to_rgb(data, cmap2d=cmap2d,
                             huenorm=huenorm, huevmin=huevmin,
                             huevmax=huevmax, lightnorm=lightnorm,
                             lightvmin=lightvmin, lightvmax=lightvmax)
    im = ax.imshow(rgb_data, **kwargs)
    return im 
Example #21
Source File: cmaps.py    From xcube with MIT License 5 votes vote down vote up
def _get_custom_colormap(colortext):
    try:
        colors = _get_color(colortext)
        values = get_tick_val_col(colortext)
        if colors is None or values is None:
            return
        norm = plt.Normalize(min(values), max(values))
        tuples = list(zip(map(norm, values), colors))
        cmap = matplotlib.colors.LinearSegmentedColormap.from_list(colortext, tuples)
    except FileNotFoundError:
        LOG.warning('No such file or directory: "%s"' % colortext)
        return
    return cmap 
Example #22
Source File: plots.py    From nxviz with MIT License 5 votes vote down vote up
def compute_edge_colors(self):
        """Compute the edge colors."""
        data = [self.graph.edges[n][self.edge_color] for n in self.edges]
        data_reduced = sorted(list(set(data)))

        dtype = infer_data_type(data)
        n_grps = num_discrete_groups(data)
        if dtype == "categorical" or dtype == "ordinal":
            if n_grps <= 8:
                cmap = get_cmap(
                    cmaps["Accent_{0}".format(n_grps)].mpl_colormap
                )
            else:
                cmap = n_group_colorpallet(n_grps)
        elif dtype == "continuous" and not is_data_diverging(data):
            cmap = get_cmap(cmaps["weights"])

        for d in data:
            idx = data_reduced.index(d) / n_grps
            self.edge_colors.append(cmap(idx))
        # Add colorbar if required.
        logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
        logging.debug("dtype: {0}".format(dtype))
        if len(data_reduced) > 1 and dtype == "continuous":
            self.sm = plt.cm.ScalarMappable(
                cmap=cmap,
                norm=plt.Normalize(
                    vmin=min(data_reduced),
                    vmax=max(data_reduced),  # noqa  # noqa
                ),
            )
            self.sm._A = [] 
Example #23
Source File: plots.py    From nxviz with MIT License 5 votes vote down vote up
def compute_node_colors(self):
        """Compute the node colors. Also computes the colorbar."""
        data = [self.graph.nodes[n][self.node_color] for n in self.nodes]

        if self.group_order == "alphabetically":
            data_reduced = sorted(list(set(data)))
        elif self.group_order == "default":
            data_reduced = list(unique_everseen(data))

        dtype = infer_data_type(data)
        n_grps = num_discrete_groups(data)

        if dtype == "categorical" or dtype == "ordinal":
            if n_grps <= 8:
                cmap = get_cmap(
                    cmaps["Accent_{0}".format(n_grps)].mpl_colormap
                )
            else:
                cmap = n_group_colorpallet(n_grps)
        elif dtype == "continuous" and not is_data_diverging(data):
            cmap = get_cmap(cmaps["continuous"].mpl_colormap)
        elif dtype == "continuous" and is_data_diverging(data):
            cmap = get_cmap(cmaps["diverging"].mpl_colormap)

        for d in data:
            idx = data_reduced.index(d) / n_grps
            self.node_colors.append(cmap(idx))

        # Add colorbar if required.ListedColormap
        logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
        logging.debug("dtype: {0}".format(dtype))
        if len(data_reduced) > 1 and dtype == "continuous":
            self.sm = plt.cm.ScalarMappable(
                cmap=cmap,
                norm=plt.Normalize(
                    vmin=min(data_reduced),
                    vmax=max(data_reduced),  # noqa  # noqa
                ),
            )
            self.sm._A = [] 
Example #24
Source File: utils.py    From SymJAX with Apache License 2.0 5 votes vote down vote up
def create_cmap(values, colors):

    from matplotlib.pyplot import Normalize
    import matplotlib

    norm = Normalize(min(values), max(values))
    tuples = list(zip(map(norm, values), colors))
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
    return cmap, norm 
Example #25
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_LogNorm():
    """
    LogNorm ignored clip, now it has the same
    behavior as Normalize, e.g., values > vmax are bigger than 1
    without clip, with clip they are 1.
    """
    ln = mcolors.LogNorm(clip=True, vmax=5)
    assert_array_equal(ln([1, 6]), [0, 1.0]) 
Example #26
Source File: core.py    From nelpy with MIT License 5 votes vote down vote up
def colorline(x, y, cmap=None, cm_range=(0, 0.7), **kwargs):
    """Colorline plots a trajectory of (x,y) points with a colormap"""

    # plt.plot(x, y, '-k', zorder=1)
    # plt.scatter(x, y, s=40, c=plt.cm.RdBu(np.linspace(0,1,40)), zorder=2, edgecolor='k')

    assert len(cm_range)==2, "cm_range must have (min, max)"
    assert len(x) == len(y), "x and y must have the same number of elements!"

    ax = kwargs.get('ax', plt.gca())
    lw = kwargs.get('lw', 2)
    if cmap is None:
        cmap=plt.cm.Blues_r

    t = np.linspace(cm_range[0], cm_range[1], len(x))

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 1),
                        zorder=50)
    lc.set_array(t)
    lc.set_linewidth(lw)

    ax.add_collection(lc)

    return lc 
Example #27
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        assert len(recwarn) == 0
        recwarn.clear() 
Example #28
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #29
Source File: complexity_delay.py    From NeuroKit with MIT License 4 votes vote down vote up
def _embedding_delay_plot(
    signal, metric_values, tau_sequence, tau=1, metric="Mutual Information", ax0=None, ax1=None, plot="2D"
):

    # Prepare figure
    if ax0 is None and ax1 is None:
        fig = plt.figure(constrained_layout=False)
        spec = matplotlib.gridspec.GridSpec(ncols=1, nrows=2, height_ratios=[1, 3], width_ratios=[2])
        ax0 = fig.add_subplot(spec[0])
        if plot == "2D":
            ax1 = fig.add_subplot(spec[1])
        elif plot == "3D":
            ax1 = fig.add_subplot(spec[1], projection="3d")
    else:
        fig = None

    ax0.set_title("Optimization of Delay (tau)")
    ax0.set_xlabel("Time Delay (tau)")
    ax0.set_ylabel(metric)
    ax0.plot(tau_sequence, metric_values, color="#FFC107")
    ax0.axvline(x=tau, color="#E91E63", label="Optimal delay: " + str(tau))
    ax0.legend(loc="upper right")
    ax1.set_title("Attractor")
    ax1.set_xlabel("Signal [i]")
    ax1.set_ylabel("Signal [i-" + str(tau) + "]")

    # Get data points, set axis limits
    embedded = complexity_embedding(signal, delay=tau, dimension=3)
    x = embedded[:, 0]
    y = embedded[:, 1]
    z = embedded[:, 2]
    ax1.set_xlim(x.min(), x.max())
    ax1.set_ylim(x.min(), x.max())

    # Colors
    norm = plt.Normalize(z.min(), z.max())
    cmap = plt.get_cmap("plasma")
    colors = cmap(norm(x))

    # Attractor for 2D vs 3D
    if plot == "2D":
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = matplotlib.collections.LineCollection(segments, cmap="plasma", norm=norm)
        lc.set_array(z)
        ax1.add_collection(lc)

    elif plot == "3D":
        points = np.array([x, y, z]).T.reshape(-1, 1, 3)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        for i in range(len(x) - 1):
            seg = segments[i]
            (l,) = ax1.plot(seg[:, 0], seg[:, 1], seg[:, 2], color=colors[i])
            l.set_solid_capstyle("round")
        ax1.set_zlabel("Signal [i-" + str(2 * tau) + "]")

    return fig 
Example #30
Source File: plot.py    From deephar with MIT License 4 votes vote down vote up
def plot_skeleton_2d(subplot, skel, h=None, w=None,
        joints=True, links=True, scale=16, lw=4):

    s = skel.copy()
    num_joints = len(s)
    assert ((num_joints == 16) or (num_joints == 17)) or (num_joints == 20), \
            'Unsupported number of joints (%d)' % num_joints

    color, cmap, links = _get_poselayout(num_joints)

    x = s[:,0]
    y = s[:,1]
    v = s > -1e6
    v = v.any(axis=1).astype(np.float32)

    # Convert normalized skeletons to image coordinates.
    if w is not None:
        x *= w
    if h is not None:
        y *= h

    if joints:
        for i in range(len(v)):
            if v[i] > 0:
                c = color[cmap[i]]
                subplot.scatter(x=x[i], y=y[i], c=c, lw=lw, s=scale, zorder=2)

    if links:
        for i in links:
            if ((v[i[0]] > 0) and (v[i[1]] > 0)):
                c = color[cmap[i[0]]]
                subplot.plot(x[i], y[i], lw=lw, c=c, zorder=1)


# def drawhm(hm, zero_clip=False, vmax=None, filename=None):
    # #heatmaps = np.transpose(heatmaps, (0, 3, 1, 2))
    # fb = hm.copy()

    # if zero_clip:
        # fb = (fb > 0) * fb

    # vmin = fb.min()
    # if vmax is None:
        # vmax = fb.max()

    # print (vmin, vmax)

    # cmap = plt.cm.jet
    # norm = plt.Normalize(vmin=vmin, vmax=vmax)
    # image = cmap(norm(fb))
    # print (filename)
    # if filename is not None:
        # plt.imsave(filename, image)
    # else:
        # plt.show(image)
    # plt.close()