Python matplotlib.pyplot.NullLocator() Examples

The following are code examples for showing how to use matplotlib.pyplot.NullLocator(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis() 
Example 2
Project: stackednet   Author: zsdonghao   File: stacked_autoencoder.py    MIT License 6 votes vote down vote up
def visualize_assquare_W(D1, n_units_l1, second=10, saveable=False, idx=None, fig_idx=0):
        plt.ion()
        fig = plt.figure(fig_idx)      # show all feature images
        size = D1.shape[0]

        num_r = int(np.round(np.sqrt(n_units_l1)))  # 每行显示的个数   若25个hidden unit -> 每行显示5个
        count = 1
        for row in range(1,num_r+1):
            for col in range(1, int(n_units_l1/num_r)+1):
                #print(col, row, count)
                a = fig.add_subplot(int(n_units_l1/num_r), num_r, count)
                # plt.imshow(np.reshape(D1.get_value()[:,count-1],(28,28)), cmap='gray')
                plt.imshow(np.reshape(D1[:,count-1] / np.sqrt( (D1[:,count-1]**2).sum()) ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest")
                plt.gca().xaxis.set_major_locator(plt.NullLocator())    # 不显示刻度(tick)
                plt.gca().yaxis.set_major_locator(plt.NullLocator())
                count = count + 1
        # plt.title('All feature groups from GVM')
        # plt.show()
        if saveable:
            plt.savefig(str(idx)+'.pdf',format='pdf')
        else:
            plt.draw()
            plt.pause(second) 
Example 3
Project: atlantisbot   Author: johnvictorfs   File: tools.py    MIT License 6 votes vote down vote up
def plot_table(table_name: str, image_name: str, safe: bool = True):
    # https://stackoverflow.com/questions/35634238/how-to-save-a-pandas-dataframe-table-as-a-png
    df = pd.read_sql(table_name, engine)
    if safe:
        if table_name == 'amigosecreto':
            df = df.drop(['id', 'giving_to_user_id', 'receiving'], axis=1)
    fig, ax = plt.subplots(figsize=(12, 2))  # set size frame
    ax.xaxis.set_visible(False)  # hide the x axis
    ax.yaxis.set_visible(False)  # hide the y axis
    ax.set_frame_on(False)  # no visible frame
    table(ax, df, loc='upper right', colWidths=[0.17] * len(df.columns))

    # https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.savefig(f"{image_name}.tmp.png", bbox_inches='tight', pad_inches=0, transparent=True) 
Example 4
Project: sul   Author: ddddwee1   File: sulplotter.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def __init__(self, usebuffer=False, elev=None, azim=None, axis='on', axis_tick='on', no_margin=False):
		fig = plt.figure()
		self.ax = fig.add_subplot(111, projection='3d')

		if no_margin:
			# axis = 'off'
			plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
			plt.margins(0,0,0)
			# self.ax.xaxis.set_major_locator(plt.NullLocator())
			# self.ax.yaxis.set_major_locator(plt.NullLocator())
		self.ax.view_init(elev=elev, azim=azim)
		self.ax.axis(axis)
		if axis_tick=='off':
			self.ax.set_xticklabels([])
			self.ax.set_yticklabels([])
			self.ax.set_zticklabels([])
		self.lines = []
		self.lines_buff = []
		self.line_pos = 0
		self.usebuffer = usebuffer
		self.fig = fig 
Example 5
Project: sul   Author: ddddwee1   File: sulplotter.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def __init__(self, usebuffer=False, elev=None, azim=None, axis='on', axis_tick='on', no_margin=False):
		fig = plt.figure()
		plt.tight_layout()
		self.ax = fig.add_subplot(111)
		if no_margin:
			axis = 'off'
			plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
			plt.margins(0,0)
			self.ax.xaxis.set_major_locator(plt.NullLocator())
			self.ax.yaxis.set_major_locator(plt.NullLocator())
		self.ax.axis(axis)
		if axis=='off':
			self.ax.set_xticklabels([])
			self.ax.set_yticklabels([])
		self.lines = []
		self.lines_buff = []
		self.line_pos = 0
		self.usebuffer = usebuffer
		self.fig = fig 
Example 6
Project: python3_ios   Author: holzschu   File: hinton_demo.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis() 
Example 7
Project: color_recognizer   Author: michtesar   File: hinton.py    MIT License 6 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis()

    return ax 
Example 8
Project: hicstuff   Author: baudrly   File: vizmap.py    GNU General Public License v3.0 6 votes vote down vote up
def save_matrix(array, filename, vmax=None, dpi=DEFAULT_DPI):
    """A function that performs all the tedious matplotlib
    magic to draw a 2D array with as few parameters and
    as little whitespace as possible.

    Adjusted from https://github.com/koszullab/metaTOR
    """

    if vmax is None:
        vmax = np.percentile(array, DEFAULT_SATURATION_THRESHOLD)
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.figure()
    if SEABORN:
        sns.heatmap(array, vmax=vmax, cmap="Reds")
    else:
        plt.imshow(array, vmax=vmax, cmap="Reds", interpolation="none")
        plt.colorbar()
    plt.axis("off")
    plt.savefig(filename, bbox_inches="tight", pad_inches=0.0, dpi=dpi)
    plt.close() 
Example 9
Project: CNNArt   Author: thomaskuestner   File: matplotlibwidget.py    Apache License 2.0 6 votes vote down vote up
def Weights_opt(self, matrix, max_weight=None, ax=None):

        ax = ax if ax is not None else plt.gca()

        if not max_weight:
            max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

        ax.patch.set_facecolor('gray')
        ax.set_aspect('equal', 'box')
        ax.xaxis.set_major_locator(plt.NullLocator())
        ax.yaxis.set_major_locator(plt.NullLocator())

        for (x, y), w in np.ndenumerate(matrix):
            color = 'white' if w > 0 else 'black'
            size = np.sqrt(np.abs(w))
            rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                                 facecolor=color, edgecolor=color)
            ax.add_patch(rect)

        ax.autoscale_view()
        ax.invert_yaxis() 
Example 10
Project: connecting_the_dots   Author: autonomousvision   File: plt.py    MIT License 5 votes vote down vote up
def save(path, remove_axis=False, dpi=300, fig=None):
  if fig is None:
    fig = plt.gcf()
  dirname = os.path.dirname(path)
  if dirname != '' and not os.path.exists(dirname):
    os.makedirs(dirname)
  if remove_axis:
    for ax in fig.axes:
      ax.axis('off')
      ax.margins(0,0)
    fig.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    for ax in fig.axes:
      ax.xaxis.set_major_locator(plt.NullLocator())
      ax.yaxis.set_major_locator(plt.NullLocator())
  fig.savefig(path, dpi=dpi, bbox_inches='tight', pad_inches=0) 
Example 11
Project: ble5-nrf52-mac   Author: tomasero   File: test_text.py    MIT License 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 12
Project: LapSRN-tensorflow   Author: zjuela   File: visualize.py    Apache License 2.0 5 votes vote down vote up
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836):
    """Display a frame(image). Make sure OpenAI Gym render() is disable before using it.

    Parameters
    ----------
    I : numpy.array
        The image
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    name : a string
        A name to save the image, if saveable is True.
    cmap : None or string
        'gray' for greyscale, None for default, etc.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> env = gym.make("Pong-v0")
    >>> observation = env.reset()
    >>> tl.visualize.frame(observation)
    """
    if saveable is False:
        plt.ion()
    fig = plt.figure(fig_idx)      # show all feature images

    if len(I.shape) and I.shape[-1]==1:     # (10,10,1) --> (10,10)
        I = I[:,:,0]

    plt.imshow(I, cmap)
    plt.title(name)
    # plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
    # plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 13
Project: labelKeypoint   Author: Jeff-sjtu   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_label(label, img, label_names, colormap=None):
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0, hspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if colormap is None:
        colormap = label_colormap(len(label_names))

    label_viz = label2rgb(label, img, n_labels=len(label_names))
    plt.imshow(label_viz)
    plt.axis('off')

    plt_handlers = []
    plt_titles = []
    for label_value, label_name in enumerate(label_names):
        fc = colormap[label_value]
        p = plt.Rectangle((0, 0), 1, 1, fc=fc)
        plt_handlers.append(p)
        plt_titles.append(label_name)
    plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)

    f = io.BytesIO()
    plt.savefig(f, bbox_inches='tight', pad_inches=0)
    plt.cla()
    plt.close()

    out_size = (img.shape[1], img.shape[0])
    out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
    out = np.asarray(out)
    return out 
Example 14
Project: python3_ios   Author: holzschu   File: test_text.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 15
Project: mask-rcnn-labelme   Author: wendelue   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_label(label, img, label_names, colormap=None):
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0, hspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if colormap is None:
        colormap = label_colormap(len(label_names))

    label_viz = label2rgb(label, img, n_labels=len(label_names))
    plt.imshow(label_viz)
    plt.axis('off')

    plt_handlers = []
    plt_titles = []
    for label_value, label_name in enumerate(label_names):
        fc = colormap[label_value]
        p = plt.Rectangle((0, 0), 1, 1, fc=fc)
        plt_handlers.append(p)
        plt_titles.append(label_name)
    plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)

    f = io.BytesIO()
    plt.savefig(f, bbox_inches='tight', pad_inches=0)
    plt.cla()
    plt.close()

    out_size = (img.shape[1], img.shape[0])
    out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
    out = np.asarray(out)
    return out 
Example 16
Project: metaTOR   Author: koszullab   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def spaceless_pdf_plot_maker(array, filename, vmax=None, dpi=DEFAULT_DPI):
    """Draw a pretty plot from an array

    A function that performs all the tedious matplotlib
    magic to draw a 2D array with as few parameters and
    as little whitespace as possible.

    Parameters
    ----------
    array : array_like
        The input array to draw.
    filename : file, str or pathlib.Path
        The output image to save the array into.
    vmax : float, optional
        The default saturation threshold for the array. If set to None, the
        80th percentile value of the array is chosen. Default is None.
    dpi : int, optional
        Dots per inch (DPI) of the output image. Default is 200.
    """

    if vmax is None:
        vmax = np.percentile(array, DEFAULT_SATURATION_THRESHOLD)
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.figure()
    if SEABORN:
        sns.heatmap(array, vmax=vmax, cmap="Reds")
    else:
        plt.imshow(array, vmax=vmax, cmap="Reds", interpolation="none")
        plt.colorbar()
    plt.savefig(filename, bbox_inches="tight", pad_inches=0.0, dpi=dpi)
    plt.close() 
Example 17
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_text.py    MIT License 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 18
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_text.py    MIT License 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 19
Project: lang2program   Author: kelvinguu   File: plot.py    Apache License 2.0 5 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None, xtick=None, ytick=None, inverted_color=False):
    """Draw Hinton diagram for visualizing a weight matrix.

    Copied from: http://matplotlib.org/examples/specialty_plots/hinton_demo.html
    """
    ax = ax if ax is not None else plt.gca()
    if not max_weight:
        max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        if inverted_color:
            color = 'black' if w > 0 else 'white'
        else:
            color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w))
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis()

    if xtick:
        ax.set_xticks(np.arange(matrix.shape[0]))
        ax.set_xticklabels(xtick)
    if ytick:
        ax.set_yticks(np.arange(matrix.shape[1]))
        ax.set_yticklabels(ytick)
    return ax 
Example 20
Project: lang2program   Author: kelvinguu   File: plot.py    Apache License 2.0 5 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None, xtick=None, ytick=None, inverted_color=False):
    """Draw Hinton diagram for visualizing a weight matrix.

    Copied from: http://matplotlib.org/examples/specialty_plots/hinton_demo.html
    """
    ax = ax if ax is not None else plt.gca()
    if not max_weight:
        max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        if inverted_color:
            color = 'black' if w > 0 else 'white'
        else:
            color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w))
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis()

    if xtick:
        ax.set_xticks(np.arange(matrix.shape[0]))
        ax.set_xticklabels(xtick)
    if ytick:
        ax.set_yticks(np.arange(matrix.shape[1]))
        ax.set_yticklabels(ytick)
    return ax 
Example 21
Project: Blackjack-Tracker   Author: martinabeleda   File: test_text.py    MIT License 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 22
Project: deepsleepnet   Author: akaraspt   File: visualize.py    Apache License 2.0 5 votes vote down vote up
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836):
    """Display a frame(image). Make sure OpenAI Gym render() is disable before using it.

    Parameters
    ----------
    I : numpy.array
        The image
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    name : a string
        A name to save the image, if saveable is True.
    cmap : None or string
        'gray' for greyscale, None for default, etc.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> env = gym.make("Pong-v0")
    >>> observation = env.reset()
    >>> tl.visualize.frame(observation)
    """
    if saveable is False:
        plt.ion()
    fig = plt.figure(fig_idx)      # show all feature images

    if len(I.shape) and I.shape[-1]==1:     # (10,10,1) --> (10,10)
        I = I[:,:,0]

    plt.imshow(I, cmap)
    plt.title(name)
    # plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
    # plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 23
Project: smp_base   Author: x75   File: plot_utils.py    MIT License 5 votes vote down vote up
def savefig_plotonly():
    plt.axis('off')
    plt.gca().set_axis_off()
    plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
    plt.margins(0,0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    # savefig("filename.pdf", bbox_inches = 'tight', pad_inches = 0)
    # fig.savefig(inputFile.replace(".wav", "_thumb1.png"), dpi=300)
    fig.savefig(thumbnailWrapperFileName3Png, bbox_inches = 'tight', pad_inches = 0, dpi=300) 
Example 24
Project: project-origin   Author: kourgeorge   File: dashboard.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):

        self._fig = plt.figure(figsize=(9, 5), dpi=120, facecolor='w')
        self._fig.canvas.set_window_title('Origin Dashboard')
        self._axes_pop = self._fig.add_subplot(221)
        self._axes_pop.set_ylabel('Population Size')
        self._line_pop, = self._axes_pop.plot([], [], '-', label=self._axes_pop.yaxis.label.get_text())
        self._axes_age = self._axes_pop.twinx()
        self._axes_age.set_ylabel('AVG Age')
        self._line_age, = self._axes_age.plot([], [], 'y-', label=self._axes_age.yaxis.label.get_text())
        self._axes_pop.legend([self._line_pop, self._line_age],
                              [self._line_pop.get_label(), self._line_age.get_label()], loc=0)

        self._axes_aiq = self._fig.add_subplot(222)
        self._axes_aiq.set_ylabel('Population AIQ')
        self._line_aiq, = self._axes_aiq.plot([], [], '-', label=self._axes_aiq.yaxis.label.get_text())
        self._axes_aiq.set_ylim(bottom=0, top=1)

        self._fig_creatures_loc = self._fig.add_axes([0.05, 0.1, 0.2, 0.3])
        self._fig_creatures_loc.yaxis.set_major_locator(plt.NullLocator())
        self._fig_creatures_loc.xaxis.set_major_locator(plt.NullLocator())
        self._fig_food_loc = self._fig.add_axes([0.26, 0.1, 0.2, 0.3])
        self._fig_food_loc.yaxis.set_major_locator(plt.NullLocator())
        self._fig_food_loc.xaxis.set_major_locator(plt.NullLocator())
        self._fig_action = self._fig.add_subplot(2, 3, 6)
        self._fig_death = self._fig.add_subplot(4, 6, 16)
        self._fig_races = self._fig.add_subplot(4, 6, 22) 
Example 25
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_text.py    GNU General Public License v3.0 5 votes vote down vote up
def test_font_scaling():
    matplotlib.rcParams['pdf.fonttype'] = 42
    fig, ax = plt.subplots(figsize=(6.4, 12.4))
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_ylim(-10, 600)

    for i, fs in enumerate(range(4, 43, 2)):
        ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs) 
Example 26
Project: seqc   Author: ambrosejcarr   File: plot.py    GNU General Public License v2.0 5 votes vote down vote up
def detick(ax=None, x=True, y=True):
    """helper function for removing tick labels from an axis"""
    if not ax:
        ax = plt.gca()
    if x:
        ax.xaxis.set_major_locator(plt.NullLocator())
    if y:
        ax.yaxis.set_major_locator(plt.NullLocator()) 
Example 27
Project: seqc   Author: ambrosejcarr   File: plot.py    GNU General Public License v2.0 5 votes vote down vote up
def continuous(x, y, c=None, ax=None, colorbar=True, randomize=True,
                   remove_ticks=False, **kwargs):
        """
        wrapper for scatter wherein the coordinates x and y are colored according to a
        continuous vector c
        :param x, y: np.ndarray, coordinate data
        :param c: np.ndarray, continuous vector by which to color data points
        :param remove_ticks: remove axis ticks and labels
        :param args: additional args for scatter
        :param kwargs: additional kwargs for scatter
        :return: ax
        """

        if ax is None:
            ax = plt.gca()

        if c is None:  # plot density if no color vector is provided
            x, y, c = scatter.density_2d(x, y)

        if randomize:
            ind = np.random.permutation(len(x))
        else:
            ind = np.argsort(c)

        sm = ax.scatter(x[ind], y[ind], c=c[ind], **kwargs)
        if remove_ticks:
            ax.xaxis.set_major_locator(plt.NullLocator())
            ax.yaxis.set_major_locator(plt.NullLocator())
        if colorbar:
            cb = plt.colorbar(sm)
            cb.ax.xaxis.set_major_locator(plt.NullLocator())
            cb.ax.yaxis.set_major_locator(plt.NullLocator())
        return ax 
Example 28
Project: ddpg-curiosity-and-multi-criteria-her   Author: CDMCH   File: dynamics_loss_mapping.py    MIT License 4 votes vote down vote up
def generate_dynamics_loss_map_from_npy_records(self, file_prefix, delete_records=False):

        file_names = [file_name for file_name in os.listdir(self.working_dir)
                      if file_name.endswith(".npy") and file_name.startswith(file_prefix)]

        losses_locations_records = np.concatenate([np.load(os.path.join(self.working_dir, file_name)) for file_name in file_names],
                                          axis=0)

        max_heatmap_samples = 10000

        losses_locations_records = losses_locations_records[np.random.choice(len(losses_locations_records),
                                                             min(max_heatmap_samples, len(losses_locations_records)),
                                                             replace=False)]

        # print("\n\n\nlosses_locations_records:\n{}\n".format(losses_locations_records))
        # exit(0)

        # Add a minuscule amount of location variation in case agent doesn't move on a certain axis.

        # print("z min: {} max: {}".format(min(z), max(z)))

        losses_locations_records[:, 1:] = losses_locations_records[:, 1:] * 100 + (np.random.randn(*losses_locations_records[:, 1:].shape) / 1000)

        losses_locations_records = losses_locations_records.swapaxes(0, 1)

        z = losses_locations_records[0, :]

        idx = z.argsort()
        x, y, z = losses_locations_records[1, idx], losses_locations_records[2, idx], z[idx]

        plt.figure(figsize=(3, 3))
        plt.scatter(x, y, c=z, s=80, edgecolors='', cmap=plt.cm.jet, alpha=0.5)
        plt.colorbar()
        plt.xlim(0, 100)
        plt.ylim(0, 100)

        im = plt.imread(os.path.join(self.working_dir, 'level.png'))
        plt.imshow(im, extent=[0, 100, 0, 100], aspect='auto')
        plt.axis('equal')
        plt.axis('off')
        plt.margins(0, 0)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.title("Dynamics Loss " + file_prefix)

        heatmap_image_path = os.path.join(self.working_dir, "{}_dynamics_loss.png".format(file_prefix))
        plt.savefig(heatmap_image_path, transparent=False, bbox_inches='tight', pad_inches=0)

        plt.close()

        if delete_records:
            for file_name in file_names:
                try:
                    os.remove(os.path.join(self.working_dir, file_name))
                except OSError:
                    pass

        return heatmap_image_path 
Example 29
Project: Semantic-Segmentation-using-Adversarial-Networks   Author: oyam   File: utils.py    MIT License 4 votes vote down vote up
def draw_label(label, img, n_class, label_titles, bg_label=0):
    """Convert label to rgb with label titles.

    @param label_title: label title for each labels.
    @type label_title: dict
    """
    from PIL import Image
    from scipy.misc import fromimage
    from skimage.color import label2rgb
    from skimage.transform import resize
    colors = labelcolormap(n_class)
    label_viz = label2rgb(label, img, colors=colors[1:], bg_label=bg_label)
    # label 0 color: (0, 0, 0, 0) -> (0, 0, 0, 255)
    label_viz[label == 0] = 0

    # plot label titles on image using matplotlib
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0, hspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.axis('off')
    # plot image
    plt.imshow(label_viz)
    # plot legend
    plt_handlers = []
    plt_titles = []
    for label_value in np.unique(label):
        if label_value not in label_titles:
            continue
        fc = colors[label_value]
        p = plt.Rectangle((0, 0), 1, 1, fc=fc)
        plt_handlers.append(p)
        plt_titles.append(label_titles[label_value])
    plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=0.5)
    # convert plotted figure to np.ndarray
    f = StringIO.StringIO()
    plt.savefig(f, bbox_inches='tight', pad_inches=0)
    result_img_pil = Image.open(f)
    result_img = fromimage(result_img_pil, mode='RGB')
    result_img = resize(result_img, img.shape, preserve_range=True)
    result_img = result_img.astype(img.dtype)
    return result_img 
Example 30
Project: skultrafast   Author: Tillsten   File: plot_helpers.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def nice_lft_map(tup, taus, coefs, show_sums=False, **kwargs):
    cmap = kwargs.pop('cmap', 'seismic')
    plt.figure(1, figsize=(6, 4))
    ax = plt.subplot(111)
    #norm = SymLogNorm(linthresh=0.3)
    norm = kwargs.pop('norm', MidPointNorm(0))

    m = np.abs(coefs[:, :]).max()
    c = ax.pcolormesh(tup.wl,
                      taus[:],
                      coefs[:, :],
                      cmap=cmap,
                      vmin=-m,
                      vmax=m,
                      norm=norm,
                      **kwargs)
    cb = plt.colorbar(c, pad=0.01)

    cb.set_label('Amplitude')
    ax.set_yscale('log')
    plt.autoscale(1, 'both', 'tight')
    #ax.set_ylim(None, 60)

    plt.minorticks_on()
    ax.set_xlabel(freq_label)
    ax.set_ylabel('Decay constant [ps]')
    if inv_freq:
        ax.invert_xaxis()
    divider = make_axes_locatable(ax)
    if show_sums:
        axt = divider.append_axes("left", size=.5, sharey=ax, pad=0.05)
        pos = np.where(coefs > 0, coefs, 0).sum(1)
        neg = np.where(coefs < 0, coefs, 0).sum(1)
        axt.plot(pos[:len(taus)], taus, 'r', label='pos.')
        axt.plot(-neg[:len(taus)], taus, 'b', label='neg.')
        axt.plot(abs(coefs).sum(1)[:len(taus)], taus, 'k', label='abs.')
        axt.legend(frameon=False, loc='best')
        axt.invert_xaxis()
        #axt.plot(out[0].T[:, wi(1513):].sum(1), taus)
        #axt.plot(3*out[0].T[:, :wi(1513)].sum(1), taus)
        #plt.autoscale(1, 'y', 'tight')
        axt.set_ylabel('Decay constant [ps]')
        axt.xaxis.set_minor_locator(plt.NullLocator())
        axt.xaxis.set_major_locator(plt.MaxNLocator(3))
        ax.tick_params(labelleft=0)
    else:
        ax.set_ylabel('Decay constant [ps]')
    if 0:
        axt = divider.append_axes("top", size=1, sharex=ax, pad=0.1)
        axt.plot(tup.wl, out[0].T[:dv.fi(taus, 0.2), :].sum(0))
        axt.plot(tup.wl, out[0].T[dv.fi(taus, 0.3):dv.fi(taus, 1), :].sum(0))
        axt.plot(tup.wl, out[0].T[dv.fi(taus, 1):dv.fi(taus, 5), :].sum(0))
        axt.plot(tup.wl, out[0].T[dv.fi(taus, 5):dv.fi(taus, 10), :].sum(0))

        axt.xaxis.tick_top()
        axt.axhline(0, c='k', zorder=1.9)
    plt.autoscale(1, 'both', 'tight') 
Example 31
Project: LapSRN-tensorflow   Author: zjuela   File: visualize.py    Apache License 2.0 4 votes vote down vote up
def W(W=None, second=10, saveable=True, shape=[28,28], name='mnist', fig_idx=2396512):
    """Visualize every columns of the weight matrix to a group of Greyscale img.

    Parameters
    ----------
    W : numpy.array
        The weight matrix
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    shape : a list with 2 int
        The shape of feature image, MNIST is [28, 80].
    name : a string
        A name to save the image, if saveable is True.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> tl.visualize.W(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012)
    """
    if saveable is False:
        plt.ion()
    fig = plt.figure(fig_idx)      # show all feature images
    size = W.shape[0]
    n_units = W.shape[1]

    num_r = int(np.sqrt(n_units))  # 每行显示的个数   若25个hidden unit -> 每行显示5个
    num_c = int(np.ceil(n_units/num_r))
    count = int(1)
    for row in range(1, num_r+1):
        for col in range(1, num_c+1):
            if count > n_units:
                break
            a = fig.add_subplot(num_r, num_c, count)
            # ------------------------------------------------------------
            # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray')
            # ------------------------------------------------------------
            feature = W[:,count-1] / np.sqrt( (W[:,count-1]**2).sum())
            # feature[feature<0.0001] = 0   # value threshold
            # if count == 1 or count == 2:
            #     print(np.mean(feature))
            # if np.std(feature) < 0.03:      # condition threshold
            #     feature = np.zeros_like(feature)
            # if np.mean(feature) < -0.015:      # condition threshold
            #     feature = np.zeros_like(feature)
            plt.imshow(np.reshape(feature ,(shape[0],shape[1])),
                    cmap='gray', interpolation="nearest")#, vmin=np.min(feature), vmax=np.max(feature))
            # plt.title(name)
            # ------------------------------------------------------------
            # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest")
            plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            count = count + 1
    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 32
Project: LapSRN-tensorflow   Author: zjuela   File: visualize.py    Apache License 2.0 4 votes vote down vote up
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362):
    """Display a group of RGB or Greyscale CNN masks.

    Parameters
    ----------
    CNN : numpy.array
        The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    name : a string
        A name to save the image, if saveable is True.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012)
    """
    # print(CNN.shape)    # (5, 5, 3, 64)
    # exit()
    n_mask = CNN.shape[3]
    n_row = CNN.shape[0]
    n_col = CNN.shape[1]
    n_color = CNN.shape[2]
    row = int(np.sqrt(n_mask))
    col = int(np.ceil(n_mask/row))
    plt.ion()   # active mode
    fig = plt.figure(fig_idx)
    count = 1
    for ir in range(1, row+1):
        for ic in range(1, col+1):
            if count > n_mask:
                break
            a = fig.add_subplot(col, row, count)
            # print(CNN[:,:,:,count-1].shape, n_row, n_col)   # (5, 1, 32) 5 5
            # exit()
            # plt.imshow(
            #         np.reshape(CNN[count-1,:,:,:], (n_row, n_col)),
            #         cmap='gray', interpolation="nearest")     # theano
            if n_color == 1:
                plt.imshow(
                        np.reshape(CNN[:,:,:,count-1], (n_row, n_col)),
                        cmap='gray', interpolation="nearest")
            elif n_color == 3:
                plt.imshow(
                        np.reshape(CNN[:,:,:,count-1], (n_row, n_col, n_color)),
                        cmap='gray', interpolation="nearest")
            else:
                raise Exception("Unknown n_color")
            plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            count = count + 1
    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 33
Project: em_examples   Author: geoscixyz   File: LinearInversion.py    MIT License 4 votes vote down vote up
def plot_G(
        self,
        N=20,
        M=100,
        p=-0.25,
        q=0.25,
        j1=1,
        jn=60,
        scale='log',
        fixed=False,
        ymin=-0.001,
        ymax=0.011
    ):
        self.set_G(
            N=N,
            M=M,
            p=p,
            q=q,
            j1=j1,
            jn=jn,

        )

        _, s, _ = np.linalg.svd(self.G, full_matrices=False)

        matplotlib.rcParams['font.size']=14

        fig=plt.figure(figsize=(10, 4))

        gs1 = gridspec.GridSpec(1, 4)
        ax1 = plt.subplot(gs1[0, :3])
        ax2 = plt.subplot(gs1[0, 3:])

        ax1.plot(self.mesh.vectorCCx, self.G.T)
        if fixed:
            ax1.set_ylim(ymin, ymax)
        ax1.set_xlabel("x")
        ax1.set_ylabel("g(x)")

        ax2.plot(np.arange(self.N)+1, s, 'ro')
        ax2.set_xlabel("")
        ax2.set_title("singular values", fontsize=12)
        ax2.set_xscale(scale)
        ax2.set_yscale(scale)
        ax2.xaxis.set_major_locator(plt.NullLocator())
        ax2.xaxis.set_minor_locator(plt.NullLocator())
        ax2.xaxis.set_major_formatter(plt.NullFormatter())
        ax2.xaxis.set_minor_formatter(plt.NullFormatter())

        plt.tight_layout()
        plt.show() 
Example 34
Project: DKFZBiasFilter   Author: DKFZ-ODCF   File: readbiasplots.py    GNU General Public License v3.0 4 votes vote down vote up
def hinton(weight_matrix, intensity_matrix, cmap, vmin, vmax, max_weight=None, ax=None):
    """
        Draw Hinton diagram for visualizing a weight matrix.

        Args
        ----
          weight_matrix: np.array
          intensity_matrix: np.array
          cmap: string
            Identifier of colormap being used for plotting (e.g. "PRGn")
          vmin: float
            Minimal value to be displayed in intensity matrix
          vmax: float
            Maximal value to be displayed in intensity matrix
          max_weight: int
            Force maximal weight of weight matrix
          ax: matplotlib.axes.Axes instance
    """
    ax = ax if ax is not None else plt.gca()
    
    # Set colors for intensity matrix
    cm = plt.get_cmap(cmap)
    cNorm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
    scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=cm)
    intensity_colors = scalarMap.to_rgba(intensity_matrix)
    
    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    
    for (x,y),w in np.ndenumerate(weight_matrix):
        color = intensity_colors[x][y]
        size = 0.
        if(not(w==0)):
            size = calculateRootedSize(float(w), float(weight_matrix.max()))

        if(not(max_weight == None)):
            size = 0.
            if(not(w==0)):
                size = calculateRootedSize(float(w), float(max_weight))
        rect = plt.Rectangle([(3-y) - size / 2, x - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)
    
    plt.ylim([-1,4])
    plt.xlim(-1,4)
    ax.invert_xaxis()
    ax.invert_yaxis() 
Example 35
Project: DKFZBiasFilter   Author: DKFZ-ODCF   File: readbiasplots.py    GNU General Public License v3.0 4 votes vote down vote up
def hintonLegend(weight_matrix, intensity_matrix, text_matrix, cmap, vmin, vmax, max_weight=None, ax=None):
    """
        Draw Hinton diagram for visualizing a legend describing the number of mutations corresponding to sizes of squares.

        Args
        ----
          weight_matrix: np.array
          intensity_matrix: np.array
          text_matrix: np.array
          cmap: string
            Identifier of colormap being used for plotting (e.g. "PRGn")
          vmin: float
            Minimal value to be displayed in intensity matrix
          vmax: float
            Maximal value to be displayed in intensity matrix
          max_weight: int
            Force maximal weight of weight matrix
          ax: matplotlib.axes.Axes instance
    """
    ax = ax if ax is not None else plt.gca()
    
    # Set colors for intensity matrix
    cm = plt.get_cmap(cmap)
    cNorm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
    scalarMap = matplotlib.cm.ScalarMappable(norm=cNorm, cmap=cm)
    intensity_colors = scalarMap.to_rgba(intensity_matrix)
    
    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    
    for (x,y),w in np.ndenumerate(weight_matrix):
        color = intensity_colors[x][y]
        size = 0.
        if(not(w==0)):
            size = calculateRootedSize(float(w), float(weight_matrix.max()))

        if(not(max_weight == None)):
            size = 0.
            if(not(w==0)):
                size = calculateRootedSize(float(w), float(max_weight))
        rect = plt.Rectangle([(3-y) - size / 2, x - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    for (x,y),w in np.ndenumerate(text_matrix):
        ax.add_patch(rect)
        plt.text(3-y, x, w)

    
    plt.ylim([-1,4])
    plt.xlim(-1,4)
    ax.invert_xaxis()
    ax.invert_yaxis() 
Example 36
Project: pcay   Author: zpace   File: find_pcs.py    MIT License 4 votes vote down vote up
def make_PC_param_regr_fig(self):
        '''
        make a figure that compares each parameter against the PC
            combination that most closely predicts it
        '''

        # how many params are there?
        # try to make a square grid, but if impossible, add another row
        nparams = self.metadata_a.shape[1]
        gs, fig = figures_tools.gen_gridspec_fig(N=nparams)

        # regression result
        A = self.find_PC_param_coeffs()

        for i in range(nparams):
            # set up subplots
            ax = fig.add_subplot(gs[i])

            x = np.column_stack([self.trn_PC_wts,
                                 np.ones(self.trn_PC_wts.shape[0])])
            y = self.metadata_a[:, i]
            y_regr = A[i].dot(x.T).flatten()
            ax.scatter(y_regr, y, marker='.', facecolor='b', edgecolor='None',
                       s=1., alpha=0.4)
            xgrid = np.linspace(y.min(), y.max())
            ax.plot(xgrid, xgrid, linestyle='--', c='g', linewidth=1)

            ax_ = ax.twinx()
            ax_.set_ylim([0., 1.])
            ax_.text(x=y_regr.min(), y=0.85, s=self.metadata_TeX[i], size=6)
            # rms
            rms = np.sqrt(np.mean((y_regr - y)**2))
            ax_.text(x=y_regr.min(), y=0.775, s='rms = {:.3f}'.format(rms),
                     size=6)

            locx = mticker.MaxNLocator(nbins=5, steps=[1, 2, 5, 10])
            locy = mticker.MaxNLocator(nbins=5, steps=[1, 2, 5, 10])
            locy_ = mticker.NullLocator()
            ax.xaxis.set_major_locator(locx)
            ax.yaxis.set_major_locator(locy)
            ax_.yaxis.set_major_locator(locy_)

            ax.tick_params(axis='both', color='k', labelsize=6)

        fig.suptitle(t=r'$Z + A \cdot X$ vs $\{P_i\}$')

        fig.savefig(os.path.join(self.basedir, 'param_regr_{}.png'.format(self.src)),
                    dpi=300) 
Example 37
Project: odin-ai   Author: imito   File: figures.py    MIT License 4 votes vote down vote up
def plot_hinton(matrix, max_weight=None, ax=None):
  '''
  Hinton diagrams are useful for visualizing the values of a 2D array (e.g.
  a weight matrix):
      Positive: white
      Negative: black
  squares, and the size of each square represents the magnitude of each value.
  * Note: performance significant decrease as array size > 50*50
  Example:
      W = np.random.rand(10,10)
      hinton_plot(W)
  '''
  from matplotlib import pyplot as plt
  """Draw Hinton diagram for visualizing a weight matrix."""
  ax = ax if ax is not None else plt.gca()

  if not max_weight:
    max_weight = 2**np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

  ax.patch.set_facecolor('gray')
  ax.set_aspect('equal', 'box')
  ax.xaxis.set_major_locator(plt.NullLocator())
  ax.yaxis.set_major_locator(plt.NullLocator())

  for (x, y), w in np.ndenumerate(matrix):
    color = 'white' if w > 0 else 'black'
    size = np.sqrt(np.abs(w))
    rect = plt.Rectangle([x - size / 2, y - size / 2],
                         size,
                         size,
                         facecolor=color,
                         edgecolor=color)
    ax.add_patch(rect)

  ax.autoscale_view()
  ax.invert_yaxis()
  return ax


# ===========================================================================
# Helper methods
# =========================================================================== 
Example 38
Project: deepsleepnet   Author: akaraspt   File: visualize.py    Apache License 2.0 4 votes vote down vote up
def W(W=None, second=10, saveable=True, shape=[28,28], name='mnist', fig_idx=2396512):
    """Visualize every columns of the weight matrix to a group of Greyscale img.

    Parameters
    ----------
    W : numpy.array
        The weight matrix
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    shape : a list with 2 int
        The shape of feature image, MNIST is [28, 80].
    name : a string
        A name to save the image, if saveable is True.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> tl.visualize.W(network.all_params[0].eval(), second=10, saveable=True, name='weight_of_1st_layer', fig_idx=2012)
    """
    if saveable is False:
        plt.ion()
    fig = plt.figure(fig_idx)      # show all feature images
    size = W.shape[0]
    n_units = W.shape[1]

    num_r = int(np.sqrt(n_units))  # 每行显示的个数   若25个hidden unit -> 每行显示5个
    num_c = int(np.ceil(n_units/num_r))
    count = int(1)
    for row in range(1, num_r+1):
        for col in range(1, num_c+1):
            if count > n_units:
                break
            a = fig.add_subplot(num_r, num_c, count)
            # ------------------------------------------------------------
            # plt.imshow(np.reshape(W[:,count-1],(28,28)), cmap='gray')
            # ------------------------------------------------------------
            feature = W[:,count-1] / np.sqrt( (W[:,count-1]**2).sum())
            # feature[feature<0.0001] = 0   # value threshold
            # if count == 1 or count == 2:
            #     print(np.mean(feature))
            # if np.std(feature) < 0.03:      # condition threshold
            #     feature = np.zeros_like(feature)
            # if np.mean(feature) < -0.015:      # condition threshold
            #     feature = np.zeros_like(feature)
            plt.imshow(np.reshape(feature ,(shape[0],shape[1])),
                    cmap='gray', interpolation="nearest")#, vmin=np.min(feature), vmax=np.max(feature))
            # plt.title(name)
            # ------------------------------------------------------------
            # plt.imshow(np.reshape(W[:,count-1] ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest")
            plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            count = count + 1
    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 39
Project: deepsleepnet   Author: akaraspt   File: visualize.py    Apache License 2.0 4 votes vote down vote up
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362):
    """Display a group of RGB or Greyscale CNN masks.

    Parameters
    ----------
    CNN : numpy.array
        The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).
    second : int
        The display second(s) for the image(s), if saveable is False.
    saveable : boolean
        Save or plot the figure.
    name : a string
        A name to save the image, if saveable is True.
    fig_idx : int
        matplotlib figure index.

    Examples
    --------
    >>> tl.visualize.CNN2d(network.all_params[0].eval(), second=10, saveable=True, name='cnn1_mnist', fig_idx=2012)
    """
    # print(CNN.shape)    # (5, 5, 3, 64)
    # exit()
    n_mask = CNN.shape[3]
    n_row = CNN.shape[0]
    n_col = CNN.shape[1]
    n_color = CNN.shape[2]
    row = int(np.sqrt(n_mask))
    col = int(np.ceil(n_mask/row))
    plt.ion()   # active mode
    fig = plt.figure(fig_idx)
    count = 1
    for ir in range(1, row+1):
        for ic in range(1, col+1):
            if count > n_mask:
                break
            a = fig.add_subplot(col, row, count)
            # print(CNN[:,:,:,count-1].shape, n_row, n_col)   # (5, 1, 32) 5 5
            # exit()
            # plt.imshow(
            #         np.reshape(CNN[count-1,:,:,:], (n_row, n_col)),
            #         cmap='gray', interpolation="nearest")     # theano
            if n_color == 1:
                plt.imshow(
                        np.reshape(CNN[:,:,:,count-1], (n_row, n_col)),
                        cmap='gray', interpolation="nearest")
            elif n_color == 3:
                plt.imshow(
                        np.reshape(CNN[:,:,:,count-1], (n_row, n_col, n_color)),
                        cmap='gray', interpolation="nearest")
            else:
                raise Exception("Unknown n_color")
            plt.gca().xaxis.set_major_locator(plt.NullLocator())    # distable tick
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            count = count + 1
    if saveable:
        plt.savefig(name+'.pdf',format='pdf')
    else:
        plt.draw()
        plt.pause(second) 
Example 40
Project: project-origin   Author: kourgeorge   File: dashboard.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def update_step_dash(self, step_stats_df):
        if step_stats_df is None or step_stats_df.empty:
            return
        self._line_pop.set_xdata(step_stats_df['Time'])
        self._line_pop.set_ydata(step_stats_df['Population'])

        self._line_age.set_xdata(step_stats_df['Time'])
        self._line_age.set_ydata(step_stats_df['Age'])

        self._line_aiq.set_xdata(step_stats_df['Time'])
        self._line_aiq.set_ydata(step_stats_df['AIQ'])

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()
        self._axes_pop.relim()
        self._axes_pop.autoscale_view()
        self._axes_age.relim()
        self._axes_age.autoscale_view()
        self._axes_aiq.relim()
        self._axes_aiq.autoscale_view()

        ## Creatures Dist
        creatures_dist = np.asarray(step_stats_df['CreaturesDist'].iloc[-1])
        self._fig_creatures_loc.clear()
        self._fig_creatures_loc.imshow(creatures_dist, cmap="Purples", aspect="auto", vmin=0, vmax=10)
        self._fig_creatures_loc.set_title('Creatures Location')
        self._fig_creatures_loc.yaxis.set_major_locator(plt.NullLocator())
        self._fig_creatures_loc.xaxis.set_major_locator(plt.NullLocator())

        ## Food Supply
        food_supply = np.asarray(step_stats_df['FoodDist'].iloc[-1])
        self._fig_food_loc.clear()
        self._fig_food_loc.imshow(food_supply, cmap="Greens", aspect="auto", vmin=0, vmax=100)
        self._fig_food_loc.set_title('Food Dist')
        self._fig_food_loc.yaxis.set_major_locator(plt.NullLocator())
        self._fig_food_loc.xaxis.set_major_locator(plt.NullLocator())

        ## Action Dist Pie
        actions_dist = np.mean(step_stats_df['ActionDist'].tail(ConfigSimulator.LOGGING_BATCH_SIZE).values, axis=0)
        self._fig_action.clear()
        patches, texts, autotexts = self._fig_action.pie(actions_dist,
                                                         startangle=90, autopct=self.make_autopct(actions_dist))
        self._fig_action.legend(patches, labels=Actions.get_actions_str(), loc=(1, 0))

        ## Death Dist Pie
        death_cause = np.mean(step_stats_df['DeathCause'].tail(ConfigSimulator.LOGGING_BATCH_SIZE).values, axis=0)
        self._fig_death.clear()
        self._fig_death.pie(death_cause, labels=['Fatigue', 'Fight', 'Elderly', 'Fall'],
                            startangle=90, autopct=self.make_autopct(death_cause))

        ## races Dist
        races = np.mean(step_stats_df['RacesDist'].tail(ConfigSimulator.LOGGING_BATCH_SIZE).values, axis=0)
        self._fig_races.clear()
        self._fig_races.pie(races, labels=[race.race_name() for race in ConfigSimulator.RACES],
                            startangle=90, autopct=self.make_autopct(races)) 
Example 41
Project: pySPM   Author: scholi   File: PCA.py    Apache License 2.0 4 votes vote down vote up
def hinton(self, max_weight=None, ax=None, matrix = None, xlabel=None, ylabel=None):
        """Draw Hinton diagram for visualizing a weight matrix."""
        if matrix is None:
            matrix = self.corr()
        ax = ax if ax is not None else plt.gca()

        if not max_weight:
            max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2))

        ax.patch.set_facecolor('lightgray')
        ax.set_aspect('equal', 'box')
        ax.xaxis.set_major_locator(plt.NullLocator())
        ax.yaxis.set_major_locator(plt.NullLocator())

        for (x, y), w in np.ndenumerate(matrix):
            color = 'red' if w > 0 else 'blue'
            size = np.sqrt(np.abs(w))
            rect = plt.Rectangle([y - size / 2, x - size / 2], size, size,
                                 facecolor=color, edgecolor=color)
            ax.add_patch(rect)

        nxticks = matrix.shape[1]
        nyticks = matrix.shape[0]
        if xlabel is None:
            xlabel = []
            for x in list(matrix.columns):
                x = re.sub(r'\^([0-9]+)',r'^{\1}', x)
                x = re.sub(r'_([0-9]+)',r'_{\1}', x)
                if x[-1] in ['+','-']:
                    x = x[:-1]+'^'+x[-1]
                xlabel.append('$'+x+'$')
        if ylabel is None:
            ylabel = list(matrix.index)
        ax.xaxis.tick_top()
        ax.set_xticks(range(nxticks))
        ax.set_xticklabels(xlabel, rotation=90)
        ax.set_yticks(range(nyticks))
        ax.set_yticklabels(ylabel)
        ax.grid(False)

        ax.autoscale_view()
        ax.invert_yaxis() 
Example 42
Project: seqc   Author: ambrosejcarr   File: plot.py    GNU General Public License v2.0 4 votes vote down vote up
def categorical(
            x, y, c, ax=None, cmap=plt.get_cmap(), legend=True, legend_kwargs=None,
            randomize=True, remove_ticks=False, *args, **kwargs):
        """
        wrapper for scatter wherein the output should be colored by a categorical vector
        c

        :param x, y: np.ndarray, coordinate data to be scattered
        :param c: categories for data
        :param ax: axis on which to scatter data
        :param cmap: color map
        :param legend: bool, if True, plot legend
        :param legend_kwargs: additional kwargs for legend
        :param randomize: if True, randomize order of plotting
        :param remove_ticks: if True, removes axes ticks and labels
        :param args: additional args for scatter
        :param kwargs: additional kwargs for scatter
        :return: ax
        """
        if not ax:  # todo replace with plt.gridspec() method
            ax = plt.gca()

        if legend_kwargs is None:
            legend_kwargs = dict()

        color_vector, category_to_color = map_categorical_to_cmap(c, cmap)

        if randomize:
            ind = np.random.permutation(len(x))
        else:
            ind = np.argsort(np.ravel(c))

        ax.scatter(np.ravel(x)[ind], np.ravel(y)[ind], c=color_vector[ind], *args,
                   **kwargs)
        if remove_ticks:
            ax.xaxis.set_major_locator(plt.NullLocator())
            ax.yaxis.set_major_locator(plt.NullLocator())

        labels, colors = zip(*sorted(category_to_color.items()))
        if legend:
            add_legend_to_categorical_vector(colors, labels, ax, markerscale=2,
                                             **legend_kwargs)
        return ax