コード例 #1
0
def produce_colour_arr(arr):

    """Function to produce a corresponding colour array for a dataset.

	Args:
		arr representing the data array you want to produce a colour array for

	Returns:
		array representing the colour array

	"""

    evenly_spaced_interval = np.linspace(0, 1, len(arr))

    #cividis colour map used for plotting
    colors = [cm.cividis(x) for x in evenly_spaced_interval]

    return colors
コード例 #2
0
ファイル: utils.py プロジェクト: Menrui/UPTAD
    def plot_graph(self, filename='loss.png'):
        fig, ax = plt.subplots()
        ax.set_xlabel('Iteration')
        ax.set_ylabel('Loss')
        ax.set_title('Training curve.')

        for i, (key, value) in enumerate(self.logs.items()):
            x = np.arange(len(value))
            y = np.array(value)
            ax.plot(x,
                    y,
                    label=key,
                    color=cm.cividis(i / len(self.logs.keys())))

        ax.legend(loc='best')

        save_path = os.path.join(self.output_dir, filename)
        logger.info('Save {}'.format(save_path))
        plt.savefig(save_path, transparent=True)
        plt.clf()
        plt.cla()
        plt.close('all')
コード例 #3
0
 def colormap(cmin, cmax, c):
     if cmin == cmax:
         c_scal = 0.5
     else:
         c_scal = (c-cmin)/(cmax-cmin)
     return color2hex(colormaps.cividis(c_scal))
コード例 #4
0
cv2.imwrite("stripes_depth.png", stripes_depth)

progression = (stripes_depth.astype(np.float64) - clip_near)
progression[progression < 0] = 0
progression = progression / progression.max()
stripe_index = (progression * 62).astype(np.int64)

# For grayscale stripes:
# stripes_color = np.zeros((im_height,im_width,3),dtype=np.uint8)

# for i_channel in range(3):
# 	stripes_color[:,:,i_channel] = progression.astype(np.uint8)

stripe_colors = (np.fliplr(
    np.array([cm.cividis(value)[0:3] for value in np.arange(0, 1.0, 1.0 / stripe_count)])) * 255).astype(np.uint8)

# For stripes with consecutively close colors:
# stripes_color = (cm.cividis(progression)[:,:,0:3] * 255).astype(np.uint8)

# For stripes with highly-varying colors:
new_stripe_colors = np.zeros((stripe_colors.shape[0] + 1, stripe_colors.shape[1]), dtype=np.uint8)

for i_color in range(stripe_count):
    new_stripe_colors[i_color + 1] = stripe_colors[i_color // 2] if i_color % 2 == 0 else stripe_colors[
        stripe_count // 2 + i_color // 2]

stripes_color = new_stripe_colors[stripe_index]

cv2.imwrite("stripes_color.png", stripes_color)
コード例 #5
0
def plot_evaluation(values,
                    info,
                    measures=[
                        'Dice', 'Jaccard', 'TPR', 'TNR', '1-GCE', 'VS', 'RI',
                        'ARI', 'MI', '1-VOI', 'ICC', '1/(1+PBD)', 'KAP', 'AUC',
                        '1/(1+HD)', '1/(1+AVD)', 'MHD'
                    ],
                    colourmap=None,
                    outfile='polar_results.png'):
    """Plot radial plot for all values and measures"""
    _min = info['minimum']
    _max = info['maximum']
    if colourmap is None:
        colourmap = [[86. / 255., 180. / 255., 233. / 255.]
                     for ii in range(values.shape[0])]
    else:
        # normalize colourmap values between 0 and 1
        colourmap = (colourmap - _min) / (_max - _min)
        # apply cividis, returns the RBG1 values for cividis, for dots
        colourmap = [[cm.cividis(ii)] for ii in colourmap]

    # elements of the circle
    N = len(measures)
    # evenly space measures around circle
    x_as = [n / float(N) * 2 * pi for n in range(N)]

    # Set color of axes
    plt.rc('axes', linewidth=0.5, edgecolor="#888888")

    # Create polar plot
    fig = plt.figure(figsize=(11, 9.5))
    gs = gridspec.GridSpec(1, 3, width_ratios=[17, 2, 1])
    ax = plt.subplot(gs[0], polar=True)

    # Set position of y-labels
    ax.set_rlabel_position(0)

    # Set color and linestyle of grid
    ax.xaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)
    ax.yaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)

    # Set yticks
    plt.yticks([0.2, 0.4, 0.6, 0.8, 1.0], ["0.2", "0.4", "0.6", "0.8", "1.0"],
               fontsize=15)
    pos = ax.get_rlabel_position()
    ax.set_rlabel_position(pos + 0.4 * 360. / float(len(measures)))

    # Plot data
    for ii in np.arange(values.shape[0]):
        xx = np.asarray(x_as) + np.random.randn(
            len(x_as)) * np.diff(x_as)[0] / 15.
        data_norm = None
        if info['logplot']:
            data_norm = matplotlib.colors.LogNorm(vmin=_min, vmax=_max)
        sc = ax.scatter(xx,
                        values[ii, :],
                        23,
                        color=colourmap[ii] * len(xx),
                        norm=data_norm,
                        zorder=3)

    # Fill area
    # close the circle
    median = list(np.median(values, axis=0))
    median += median[:1]
    upper = list(np.percentile(values, 75, axis=0))
    upper += upper[:1]
    lower = list(np.percentile(values, 25, axis=0))
    lower += lower[:1]
    x_as += x_as[:1]
    ax.plot(x_as,
            median,
            color=[86. / 255., 180. / 255., 233. / 255.],
            zorder=5)
    ax.fill_between(x_as,
                    upper,
                    lower,
                    zorder=4,
                    color=[86. / 255., 180. / 255., 233. / 255.],
                    alpha=0.3)

    # Set number of radial axes and remove labels
    plt.xticks(x_as[:-1], [])

    # Set axes limits
    plt.ylim(0, 1)

    # Draw ytick labels to make sure they fit properly
    for i in range(N):
        angle_rad = i / float(N) * 2 * pi - 0.05
        text_size = 21
        if i in {3, 8}:
            ax.text(angle_rad,
                    1.15,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        elif i in {0}:
            ax.text(angle_rad,
                    1.25,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        elif i in {1, 5, 7}:
            ax.text(angle_rad,
                    1.29,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        elif i in {4}:
            ax.text(angle_rad,
                    1.32,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="top")
        elif i in {10}:
            ax.text(angle_rad,
                    1.26,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        elif i in {6}:
            ax.text(angle_rad,
                    1.25,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        elif i in {9}:
            ax.text(angle_rad,
                    1.18,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")
        else:
            ax.text(angle_rad,
                    1.22,
                    measures[i] + "\n(m=%0.2f)" % median[i],
                    size=text_size,
                    horizontalalignment='center',
                    verticalalignment="center")

    # colorbar location on figure
    cbaxes = plt.subplot(gs[2])

    # log scaling option
    norm = None
    if info['logplot']:
        norm = matplotlib.colors.LogNorm(vmin=_min, vmax=_max)

    img = plt.imshow(np.array([[_min, _max]]),
                     aspect='auto',
                     cmap="cividis",
                     norm=norm)
    img.set_visible(False)

    # initialize colorbar
    cbar = plt.colorbar(cax=cbaxes)

    # ticks and label
    c_values = cbar.get_ticks().tolist()

    ticklabels = ["" for ii in c_values]
    if _min < np.min(c_values):
        c_values = [_min] + c_values
        ticklabels = ["%0.1f %s" %
                      (np.min(c_values), info['unit'])] + ticklabels
    else:
        ticklabels[0] = "%0.1f %s" % (np.min(c_values), info['unit'])

    if _max > np.max(c_values):
        c_values = c_values + [_max]
        ticklabels = ticklabels + [
            "%0.1f %s" % (np.max(c_values), info['unit'])
        ]
    else:
        ticklabels[-1] = "%0.1f %s" % (np.max(c_values), info['unit'])

    cbar.set_ticks(c_values)
    cbar.set_ticklabels(ticklabels)
    cbaxes.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    cbar.ax.set_ylabel(info["label"], labelpad=-20)

    # font sizes for colorbar
    cbar.ax.yaxis.label.set_size(19)
    cbar.ax.tick_params(labelsize=14)

    # Save and show polar plot
    plt.savefig(outfile)
    if info['display']:
        plt.show()
    plt.clf()
    plt.close('all')
コード例 #6
0
    #     v = np.linspace(0, np.pi, 20)
    #     radius = 4
    #     xx = radius * np.outer(np.sin(u), np.sin(v))
    #     yy = radius * np.outer(np.sin(u), np.cos(v))
    #     zzz = radius * np.outer(np.cos(u), np.ones_like(v))
    #     # https://pythonskills.co.uk/2020/01/22/plotting-a-sphere/
    #     # https://stackoverflow.com/questions/40460960/how-to-plot-a-sphere-when-we-are-given-a-central-point-and-a-radius-size
    #     # https://stackoverflow.com/questions/18897786/transparency-for-poly3dcollection-plot-in-matplotlib

    #     ax.plot_wireframe(xx, yy, zzz, rstride=1, cstride=1, color='w') #, shade=0, alpha=0.5)
    norm = Normalize(vmin=np.min(z), vmax=np.max(z))
    #     cbar = fig.colorbar(cm.ScalarMappable(norm = norm), ax=ax)
    #     cbar.ax.set_ylabel('Density')

    return ax


# In[123]:

x = np.random.normal(size=100000)
y = np.random.normal(size=100000)  #x * 3 + np.random.normal(size=100000)
z = np.random.normal(size=100000)
density_scatter(x, y, z, bins=[20, 20, 20])

# In[122]:

# https://thomas-cokelaer.info/blog/2014/09/about-matplotlib-colormap-and-how-to-get-rgb-values-of-the-map/
# https://arxiv.org/pdf/1712.01662.pdf
from matplotlib import cm
cm.cividis(0)