Python matplotlib.pyplot.pcolor() Examples

The following are code examples for showing how to use matplotlib.pyplot.pcolor(). 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: tectosaur   Author: tbenthompson   File: okada.py    MIT License 6 votes vote down vote up
def plot_interior_displacement(self, soln):
        nxy = 40
        nz = 40
        d = 0
        xs = np.linspace(-10, 10, nxy)
        zs = np.linspace(-0.1, -4.0, nz)
        X, Y, Z = np.meshgrid(xs, xs, zs)
        obs_pts = np.array([X.flatten(), Y.flatten(), Z.flatten()]).T.copy()
        t = Timer(output_fnc = logger.debug)
        interior_disp = -interior_integral(
            obs_pts, obs_pts, self.all_mesh, soln, 'elasticT3',
            3, 8, self.k_params, self.float_type,
            fmm_params = None#[100, 3.0, 3000, 25]
        ).reshape((nxy, nxy, nz, 3))
        t.report('eval %.2E interior pts' % obs_pts.shape[0])

        for i in range(nz):
            plt.figure()
            plt.pcolor(xs, xs, interior_disp[:,:,i,d])
            plt.colorbar()
            plt.title('at z = ' + ('%.3f' % zs[i]) + '    u' + ['x', 'y', 'z'][d])
            plt.show() 
Example 2
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 3
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 4
Project: Spectractor   Author: LSSTDESC   File: image_simulation.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_model(self):
        """
        Plot the star model.
        """
        x = np.linspace(self.x0 - 10 * self.fwhm, self.x0 + 10 * self.fwhm, 50)
        y = np.linspace(self.y0 - 10 * self.fwhm, self.y0 + 10 * self.fwhm, 50)
        yy, xx = np.meshgrid(x, y)
        star = self.model(xx, yy)
        fig, ax = plt.subplots(1, 1)
        im = plt.pcolor(x, y, star, cmap='jet')
        ax.grid(color='white', ls='solid')
        ax.grid(True)
        ax.set_xlabel('X [pixels]')
        ax.set_ylabel('Y [pixels]')
        ax.set_title('Star model: A=%.2f, fwhm=%.2f' % (self.amplitude, self.fwhm))
        cb = plt.colorbar(im, ax=ax)
        cb.formatter.set_powerlimits((0, 0))
        cb.locator = MaxNLocator(7, prune=None)
        cb.update_ticks()
        cb.set_label('Arbitrary units')  # ,fontsize=16)
        if parameters.DISPLAY:
            plt.show() 
Example 5
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 6 votes vote down vote up
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options):
    """Makes a pseudocolor plot.
    
    xs:
    ys:
    zs:
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    X, Y = np.meshgrid(xs, ys)
    Z = zs

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)

    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10) 
Example 6
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_filters(W, file_name):

    size = int(np.sqrt(W.shape[0] * W.shape[1])) + 1
    W = W.reshape(W.shape[0] * W.shape[1], W.shape[2], W.shape[3])

    width = W.shape[1]

    plt.figure(figsize=(15, 18))
    for i in xrange(W.shape[0]):
        plt.subplot(size, size, i+1)
        Z = W[i,:,:]
        plt.xlim(0, width)
        plt.ylim(0, width)
        #plt.axes().set_aspect('auto')
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 7
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_filters_sq(W, file_name, show_num_filters):

    size_in = W.shape[1]

    image_size = W.shape[2]

    plt.figure(figsize=(24, 15))
    for i in xrange(show_num_filters * size_in):
        plt.subplot(show_num_filters, size_in, i+1)
        Z = W[int(i / size_in), i % size_in,:,:]
        plt.xlim(0, image_size)
        plt.ylim(0, image_size)
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 8
Project: Hackathon2015   Author: wbap   File: draw_image.py    Apache License 2.0 6 votes vote down vote up
def draw_image(h, file_name):
    
    num_images = h.shape[0] * h.shape[1]
    width = h.shape[2]
    height = h.shape[3]
    graph_size = int(np.sqrt(h.shape[0] * h.shape[1])) + 1
    h = h.reshape((num_images, h.shape[2], h.shape[3]))

    plt.figure(figsize=(18, 18))
    for i in xrange(num_images):
        plt.subplot(graph_size, graph_size, i+1)
        Z = h[i,::-1,:]
        plt.xlim(0, width)
        plt.ylim(0, height)
        plt.pcolor(Z)
        plt.gray()
        plt.tick_params(labelbottom="off")
        plt.tick_params(labelleft="off")

    plt.savefig(file_name)
    plt.close() 
Example 9
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 10
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 11
Project: plastering   Author: plastering   File: plotter.py    MIT License 6 votes vote down vote up
def plot_colormap(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None):
    fig = plt.figure(figsize = figSizeIn)
    plt.pcolor(data, cmap=cmapIn)
    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if xtickTag:
        plt.xticks(xtickRange, xtickTag, fontsize=10)

    plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example 12
Project: plastering   Author: plastering   File: plotter.py    MIT License 6 votes vote down vote up
def plot_colormap_upgrade(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None, xmin=None, xmax=None, xgran=None, ymin=None, ymax=None, ygran=None):
    if xmin != None:
        y, x = np.mgrid[slice(ymin, ymax + ygran, ygran),
                slice(xmin, xmax + xgran, xgran)]
        fig = plt.figure(figsize = figSizeIn)
#       plt.pcolor(data, cmap=cmapIn)
        plt.pcolormesh(x, y, data, cmap=cmapIn)
        plt.grid(which='major',axis='both')
        plt.axis([x.min(), x.max(), y.min(), y.max()])
    else:
        plt.pcolor(data, cmap=cmapIn)

    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
#   if xtickTag:
#       plt.xticks(xtickRange, xtickTag, fontsize=10)
#
#   plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example 13
Project: plastering   Author: plastering   File: plotter.py    MIT License 6 votes vote down vote up
def plot_colormap(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None):
    fig = plt.figure(figsize = figSizeIn)
    plt.pcolor(data, cmap=cmapIn)
    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if xtickTag:
        plt.xticks(xtickRange, xtickTag, fontsize=10)

    plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example 14
Project: plastering   Author: plastering   File: plotter.py    MIT License 6 votes vote down vote up
def plot_colormap_upgrade(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None, xmin=None, xmax=None, xgran=None, ymin=None, ymax=None, ygran=None):
    if xmin != None:
        y, x = np.mgrid[slice(ymin, ymax + ygran, ygran),
                slice(xmin, xmax + xgran, xgran)]
        fig = plt.figure(figsize = figSizeIn)
#       plt.pcolor(data, cmap=cmapIn)
        plt.pcolormesh(x, y, data, cmap=cmapIn)
        plt.grid(which='major',axis='both')
        plt.axis([x.min(), x.max(), y.min(), y.max()])
    else:
        plt.pcolor(data, cmap=cmapIn)

    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
#   if xtickTag:
#       plt.xticks(xtickRange, xtickTag, fontsize=10)
#
#   plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example 15
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 16
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 17
Project: ImageFusion   Author: pfchai   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 18
Project: vsmlib   Author: undertherain   File: visualize.py    Apache License 2.0 6 votes vote down vote up
def plot_heat(ax, m, xlabels, ylabels):
    # norm = Normalize(-10,10,False)
    norm = MidpointNormalize(midpoint=0)
    ax.set_aspect('equal')
    plt.xticks(rotation=90)
    ax.set_xticks(np.arange(m.shape[1]) + 0.5, minor=False)
    ax.set_yticks(np.arange(m.shape[0]) + 0.5, minor=False)
    ax.set_xticklabels(xlabels, minor=False)
    ax.set_yticklabels(ylabels, minor=False)
    for tic in ax.xaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False
    for tic in ax.yaxis.get_major_ticks():
        tic.tick1On = tic.tick2On = False
    # ax.set_frame_on(False)
    heatmap = plt.pcolor(np.array(m), norm=norm, cmap=mpl.cm.RdBu, edgecolors="black")
    # heatmap = plt.pcolor(np.array(m), cmap=mpl.cm.RdBu, edgecolors="black")
    # im = ax.imshow(np.array(m), norm=norm, cmap=plt.cm.seismic, interpolation='none')
    # fig.colorbar(im)
    cb = plt.colorbar(heatmap, orientation='horizontal', shrink=1, aspect=40)
    # cb=plt.colorbar()
    # cb.fraction=0.1 
Example 19
Project: naminggamesal   Author: flowersteam   File: population.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def visual(self,vtype=None,ag_list=None):
		tempstr = ""
		if ag_list==None or ag_list=="all":
			ag_list=list(range(0,len(self._agentlist)))
		if vtype==None:
			tempstr += "nbagent: "+str(self._size)+"\n"
			temprep=np.matrix(np.zeros((self.get_M(),self.get_W())))
			for i in ag_list:
				temprep=temprep+self._agentlist[i].get_vocabulary_content()
			plt.figure()
			plt.title("Average on Population")
			plt.gca().invert_yaxis()
			plt.pcolor(np.array(temprep/self._size),vmin=0,vmax=1)
		else:
			if vtype=="agents":
				vtype=None
			for i in ag_list:
				print(("Agent ID: "+str(self._agentlist[i].get_id())+"\n"))
				self._agentlist[i].visual(vtype=vtype)
				print("\n") 
Example 20
Project: LATE   Author: audreyqyfu   File: scimpute.py    GNU General Public License v3.0 6 votes vote down vote up
def heatmap_vis2(arr, title='visualization of matrix', cmap="rainbow",
                 vmin=None, vmax=None, xlab='', ylab='', dir='plots'):
    '''heatmap visualization of 2D matrix, with plt.pcolor()
    cmap options PiYG for [neg, 0, posi]
    Greys Reds for [0, max]
    rainbow for [0,middle,max]'''
    if not os.path.exists(dir):
        os.makedirs(dir)
    fname = './' + dir + '/' + title + '.vis.png'

    if (vmin is None):
        vmin = np.min(arr)
    if (vmax is None):
        vmax = np.max(arr)

    fig = plt.figure(figsize=(9, 9))
    plt.pcolor(arr, cmap=cmap, vmin=vmin, vmax=vmax)
    plt.title(title)
    plt.xlabel(xlab)
    plt.ylabel(ylab)
    plt.colorbar()
    plt.savefig(fname, bbox_inches='tight')
    plt.close(fig)
    print('heatmap vis ', title, ' done') 
Example 21
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolor_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolor(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolor(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolor(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolor(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 22
Project: Cubix   Author: doctorfields   File: clouds.py    GNU General Public License v3.0 5 votes vote down vote up
def kde_plot(self, precision=50, margin=0.5):
        """ Plots (when possible) the KDE of the cloud """
        grid = Grid(self, precision, margin)
        if self.dimension == 1:
            x, = grid.mesh
            y = grid.evaluate(self.kde)
            plt.plot(x, y)
            plt.show()
        elif self.dimension == 2:
            x, y = grid.mesh
            z = grid.evaluate(self.kde)
            plt.pcolor(x, y, z, cmap='RdPu', vmin=0)
            plt.show()
        else:
            print("Can't do this") 
Example 23
Project: DeepHPMs   Author: maziarraissi   File: NavierStokes.py    MIT License 5 votes vote down vote up
def plot_solution(X_data, w_data, index):
    
    lb = X_data.min(0)
    ub = X_data.max(0)
    nn = 200
    x = np.linspace(lb[0], ub[0], nn)
    y = np.linspace(lb[1], ub[1], nn)
    X, Y = np.meshgrid(x,y)
    
    W_data = griddata(X_data, w_data.flatten(), (X, Y), method='cubic')
    
    plt.figure(index)
    plt.pcolor(X,Y,W_data, cmap = 'jet')
    plt.colorbar() 
Example 24
Project: IRL-maxent   Author: harpribot   File: maxent_gridworld.py    MIT License 5 votes vote down vote up
def main(grid_size, discount, n_trajectories, epochs, learning_rate, trajectory_length,
         trust, expert_type, random_start):
    """
    Run maximum entropy inverse reinforcement learning on the gridworld MDP.

    Plots the reward function.

    grid_size: Grid size. int.
    discount: MDP discount factor. float.
    n_trajectories: Number of sampled trajectories. int.
    epochs: Gradient descent iterations. int.
    learning_rate: Gradient descent learning rate. float.
    """

    wind = 1 - trust

    gw = gridworld.Gridworld(grid_size, wind, discount, expert_type)
    trajectories = gw.generate_trajectories(n_trajectories,
                                            trajectory_length,
                                            gw.optimal_policy, random_start=random_start)
    feature_matrix = gw.feature_matrix()
    ground_r = np.array([gw.reward(s) for s in range(gw.n_states)])
    r = maxent.irl(feature_matrix, gw.n_actions, discount,
                   gw.transition_probability, trajectories, epochs, learning_rate)

    print r.reshape((grid_size, grid_size))

    plt.subplot(1, 2, 1)
    plt.pcolor(ground_r.reshape((grid_size, grid_size)))
    plt.colorbar()
    plt.title("Groundtruth reward")
    plt.subplot(1, 2, 2)
    plt.pcolor(r.reshape((grid_size, grid_size)))
    plt.colorbar()
    plt.title("Recovered reward")
    plt.show() 
Example 25
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pcolorargs_5205():
    # Smoketest to catch issue found in gh:5205
    x = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5]
    y = [-1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0,
         0.25, 0.5, 0.75, 1.0, 1.25, 1.5]
    X, Y = np.meshgrid(x, y)
    Z = np.hypot(X, Y)

    plt.pcolor(Z)
    plt.pcolor(list(Z))
    plt.pcolor(x, y, Z)
    plt.pcolor(X, Y, list(Z)) 
Example 26
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_axes_margins():
    fig, ax = plt.subplots()
    ax.plot([0, 1, 2, 3])
    assert ax.get_ybound()[0] != 0

    fig, ax = plt.subplots()
    ax.bar([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.barh([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_xbound()[0] == 0

    fig, ax = plt.subplots()
    ax.pcolor(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.pcolorfast(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.hist(np.arange(10))
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.imshow(np.zeros((10, 10)))
    assert ax.get_xbound() == (-0.5, 9.5)
    assert ax.get_ybound() == (-0.5, 9.5) 
Example 27
Project: ble5-nrf52-mac   Author: tomasero   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def test_mixedmode():
    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    plt.figure()
    plt.pcolor(X**2 + Y**2).set_rasterized(True)


# test bbox_inches clipping 
Example 28
Project: ble5-nrf52-mac   Author: tomasero   File: test_colors.py    MIT License 5 votes vote down vote up
def test_autoscale_masked():
    # Test for #2336. Previously fully masked data would trigger a ValueError.
    data = np.ma.masked_all((12, 20))
    plt.pcolor(data)
    plt.draw() 
Example 29
Project: neural-network-animation   Author: miloharper   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def test_mixedmode():
    if not check_for('xelatex'):
        raise SkipTest('xelatex + pgf is required')

    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    plt.figure()
    plt.pcolor(X**2 + Y**2).set_rasterized(True)
    compare_figure('pgf_mixedmode.pdf')


# test bbox_inches clipping 
Example 30
Project: neural-network-animation   Author: miloharper   File: test_colors.py    MIT License 5 votes vote down vote up
def test_autoscale_masked():
    # Test for #2336. Previously fully masked data would trigger a ValueError.
    data = np.ma.masked_all((12, 20))
    plt.pcolor(data)
    plt.draw() 
Example 31
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 5 votes vote down vote up
def Contour(obj, pcolor=False, contour=True, imshow=False, **options):
    """Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use plt.imshow
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    try:
        d = obj.GetDict()
    except AttributeError:
        d = obj

    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    xs, ys = zip(*d.keys())
    xs = sorted(set(xs))
    ys = sorted(set(ys))

    X, Y = np.meshgrid(xs, ys)
    func = lambda x, y: d.get((x, y), 0)
    func = np.vectorize(func)
    Z = func(X, Y)

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)
    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10)
    if imshow:
        extent = xs[0], xs[-1], ys[0], ys[-1]
        plt.imshow(Z, extent=extent, **options) 
Example 32
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pcolorargs_5205():
    # Smoketest to catch issue found in gh:5205
    x = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5]
    y = [-1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0,
         0.25, 0.5, 0.75, 1.0, 1.25, 1.5]
    X, Y = np.meshgrid(x, y)
    Z = np.hypot(X, Y)

    plt.pcolor(Z)
    plt.pcolor(list(Z))
    plt.pcolor(x, y, Z)
    plt.pcolor(X, Y, list(Z)) 
Example 33
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_axes_margins():
    fig, ax = plt.subplots()
    ax.plot([0, 1, 2, 3])
    assert ax.get_ybound()[0] != 0

    fig, ax = plt.subplots()
    ax.bar([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.barh([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_xbound()[0] == 0

    fig, ax = plt.subplots()
    ax.pcolor(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.pcolorfast(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.hist(np.arange(10))
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.imshow(np.zeros((10, 10)))
    assert ax.get_xbound() == (-0.5, 9.5)
    assert ax.get_ybound() == (-0.5, 9.5) 
Example 34
Project: python3_ios   Author: holzschu   File: test_backend_pgf.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_mixedmode():
    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    plt.figure()
    plt.pcolor(X**2 + Y**2).set_rasterized(True)


# test bbox_inches clipping 
Example 35
Project: python3_ios   Author: holzschu   File: test_colors.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autoscale_masked():
    # Test for #2336. Previously fully masked data would trigger a ValueError.
    data = np.ma.masked_all((12, 20))
    plt.pcolor(data)
    plt.draw() 
Example 36
Project: KATE-Chinese-Large-Scale   Author: Htiango   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heatmap(data, save_file='heatmap.png'):
    plt.pcolor(data, cmap=plt.cm.jet)
    plt.savefig(save_file)
    # plt.show() 
Example 37
Project: motion-planning-playground   Author: karanchawla   File: potential_field.py    MIT License 5 votes vote down vote up
def draw_heatmap(data):
    data = np.array(data).T
    plt.pcolor(data, vmax=100.0, cmap=plt.cm.coolwarm) 
Example 38
Project: KATE   Author: hugochan   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heatmap(data, save_file='heatmap.png'):
    ax = plt.figure().gca()
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.yaxis.set_major_locator(MultipleLocator(5))
    plt.pcolor(data, cmap=plt.cm.jet)
    plt.savefig(save_file)
    # plt.show() 
Example 39
Project: linear_neuron   Author: uglyboxer   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def test_mixedmode():
    if not check_for('xelatex'):
        raise SkipTest('xelatex + pgf is required')

    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    plt.figure()
    plt.pcolor(X**2 + Y**2).set_rasterized(True)
    compare_figure('pgf_mixedmode.pdf')


# test bbox_inches clipping 
Example 40
Project: linear_neuron   Author: uglyboxer   File: test_colors.py    MIT License 5 votes vote down vote up
def test_autoscale_masked():
    # Test for #2336. Previously fully masked data would trigger a ValueError.
    data = np.ma.masked_all((12, 20))
    plt.pcolor(data)
    plt.draw() 
Example 41
Project: sv_and_isoforms_from_RNAseq   Author: NCBI-Hackathons   File: base_histogram.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def heatmap(hgrams, groups, title=None, fname=None, show=False, 
            order='spearman', srrs=None):
  """
  Future versions will include some statistical ordering. Maybe.
  Groups is either ints or strings.
  """
  from scipy.stats import spearmanr
  rows, cols = len(hgrams), max([len(h) for h in hgrams])
  plt.figure(figsize=(6,6))
  
  # Get group stuff
  uni_groups = list(set(groups))
  ngroups = len(uni_groups)
  group_dict = {n: uni_groups[n] for n in range(ngroups)}
  # Make arr for heatmap
  arr = np.zeros((rows+ngroups-1, cols)) 
  for gro in range(len(uni_groups)):
    for hg in range(len(hgrams)): # Should be same length as groups
      if groups[hg] == uni_groups[gro]:
        arr[hg+gro,:len(hgrams[hg])] = hgrams[hg]
    arr[hg+gro,:len(hgrams[hg])] = [1 if i%2==0 else 0 for i in range(len(hgrams[hg]))]
  arr = np.array(arr)
  
  # Plotting stuff!
  heatmap = plt.pcolor(arr)
  plt.xlabel('Base number')
  plt.ylabel('Accession number')
  for gr in range(ngroups):
    plt.text(gr*20,0, '%i: %s' %(gr, uni_groups[gr]))
  if srrs is not None:
    plt.x
  if fname is not None:
    plt.savefig(fname)
  if show:
    plt.show()
  return 
Example 42
Project: CRFBiaffineParser   Author: wfxedu   File: network_crf.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 43
Project: CRFBiaffineParser   Author: wfxedu   File: network.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 44
Project: CRFBiaffineParser   Author: wfxedu   File: network_scores.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 45
Project: Think-Bayes   Author: foamliu   File: thinkplot.py    Apache License 2.0 5 votes vote down vote up
def Contour(obj, pcolor=False, contour=True, imshow=False, **options):
    """Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use pyplot.imshow
    options: keyword args passed to pyplot.pcolor and/or pyplot.contour
    """
    try:
        d = obj.GetDict()
    except AttributeError:
        d = obj

    Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    xs, ys = zip(*d.keys())
    xs = sorted(set(xs))
    ys = sorted(set(ys))

    X, Y = np.meshgrid(xs, ys)
    func = lambda x, y: d.get((x, y), 0)
    func = np.vectorize(func)
    Z = func(X, Y)

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = pyplot.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        pyplot.pcolormesh(X, Y, Z, **options)
    if contour:
        cs = pyplot.contour(X, Y, Z, **options)
        pyplot.clabel(cs, inline=1, fontsize=10)
    if imshow:
        extent = xs[0], xs[-1], ys[0], ys[-1]
        pyplot.imshow(Z, extent=extent, **options) 
Example 46
Project: probability-distribution-network   Author: tmagara   File: visualize.py    MIT License 5 votes vote down vote up
def save_2d(self, file_path):
        model = self.target
        samples = self.samples

        seaborn.set_style("whitegrid")

        xp = model.xp

        x = xp.linspace(-0.5, 0.5, 65, dtype=xp.float32)
        x1, x2 = xp.broadcast_arrays(x[:, None], x[None])
        x = xp.stack((x1, x2), 2)
        x = xp.reshape(x, (-1, 2))

        p = model.calculate_p(x)
        p = chainer.functions.prod(p, 1, True)
        p = chainer.functions.reshape(p, x1.shape)
        p = chainer.backends.cuda.to_cpu(p.data)

        pyplot.figure()

        rows = 2 if self.inverse is None else 3

        ax1 = pyplot.subplot(1, rows, 1)
        ax1.set_aspect('equal')
        pyplot.scatter(samples[:, 0], samples[:, 1], 1)

        ax2 = pyplot.subplot(1, rows, 2)
        ax2.set_aspect('equal')
        pyplot.pcolor(p)

        if self.inverse is not None:
            uniform = xp.random.uniform(size=samples.shape, dtype=samples.dtype)
            generated = self.inverse.sample(uniform).data
            generated = chainer.backends.cuda.to_cpu(generated)

            ax3 = pyplot.subplot(1, rows, 3)
            ax3.set_aspect('equal')
            pyplot.scatter(generated[:, 0], generated[:, 1], 1)

        pyplot.savefig(file_path, bbox_inches='tight')
        pyplot.close() 
Example 47
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pcolorargs_5205():
    # Smoketest to catch issue found in gh:5205
    x = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5]
    y = [-1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0,
         0.25, 0.5, 0.75, 1.0, 1.25, 1.5]
    X, Y = np.meshgrid(x, y)
    Z = np.hypot(X, Y)

    plt.pcolor(Z)
    plt.pcolor(list(Z))
    plt.pcolor(x, y, Z)
    plt.pcolor(X, Y, list(Z)) 
Example 48
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_axes_margins():
    fig, ax = plt.subplots()
    ax.plot([0, 1, 2, 3])
    assert ax.get_ybound()[0] != 0

    fig, ax = plt.subplots()
    ax.bar([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.barh([0, 1, 2, 3], [1, 1, 1, 1])
    assert ax.get_xbound()[0] == 0

    fig, ax = plt.subplots()
    ax.pcolor(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.pcolorfast(np.zeros((10, 10)))
    assert ax.get_xbound() == (0, 10)
    assert ax.get_ybound() == (0, 10)

    fig, ax = plt.subplots()
    ax.hist(np.arange(10))
    assert ax.get_ybound()[0] == 0

    fig, ax = plt.subplots()
    ax.imshow(np.zeros((10, 10)))
    assert ax.get_xbound() == (-0.5, 9.5)
    assert ax.get_ybound() == (-0.5, 9.5) 
Example 49
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def test_mixedmode():
    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    plt.figure()
    plt.pcolor(X**2 + Y**2).set_rasterized(True)


# test bbox_inches clipping 
Example 50
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_colors.py    MIT License 5 votes vote down vote up
def test_autoscale_masked():
    # Test for #2336. Previously fully masked data would trigger a ValueError.
    data = np.ma.masked_all((12, 20))
    plt.pcolor(data)
    plt.draw()