Python matplotlib.pyplot.pcolor() Examples

The following are 30 code examples of matplotlib.pyplot.pcolor(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: NavierStokes.py    From PINNs with MIT License 7 votes vote down vote up
def plot_solution(X_star, u_star, index):
    
    lb = X_star.min(0)
    ub = X_star.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)
    
    U_star = griddata(X_star, u_star.flatten(), (X, Y), method='cubic')
    
    plt.figure(index)
    plt.pcolor(X,Y,U_star, cmap = 'jet')
    plt.colorbar() 
Example #2
Source File: plotter.py    From plastering with 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 #3
Source File: plotter.py    From plastering with 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 #4
Source File: plotter.py    From plastering with 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 #5
Source File: plotter.py    From plastering with 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 #6
Source File: test_axes.py    From coffeegrindsize with 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 #7
Source File: data_class.py    From MIDI-VAE with MIT License 6 votes vote down vote up
def draw_pianoroll(pianoroll, name='Notes', show=False, save_path=''):

    cm = matplotlib.cm.get_cmap('Greys')
    notes_color = cm(1.0)

    notes_patch = mpatches.Patch(color=notes_color, label=name)

    plt.figure(figsize=(20.0, 10.0))
    plt.title('Pianoroll Pitch-plot of ' + name, fontsize=10)
    plt.legend(handles=[notes_patch], loc='upper right', prop={'size': 8})

    plt.pcolor(pianoroll, cmap='Greys', vmin=0, vmax=np.max(pianoroll))
    if show:
        plt.show()
    if len(save_path) > 0:
        plt.savefig(save_path)
        tikz_save(save_path + ".tex", encoding='utf-8', show_info=False)
    plt.close() 
Example #8
Source File: test_axes.py    From ImageFusion with 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 #9
Source File: test_axes.py    From python3_ios with 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
Source File: thinkplot.py    From DataExploration with 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 pyplot.pcolor and/or pyplot.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 = 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) 
Example #11
Source File: thinkplot.py    From Lie_to_me with 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 #12
Source File: test_axes.py    From twitter-stock-recommendation with 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 #13
Source File: test_axes.py    From neural-network-animation with 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 #14
Source File: smokes_friends_cancer.py    From logictensornetworks with MIT License 5 votes vote down vote up
def plt_heatmap(df):
    # display the result of a nxm pandas dataframe in a heatmap
    plt.pcolor(df)
    plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
    plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
    plt.colorbar() 
Example #15
Source File: giplt.py    From geoist with MIT License 5 votes vote down vote up
def squaremesh(mesh, prop, cmap=pyplot.cm.jet, vmin=None, vmax=None):
    """
    Make a pseudo-color plot of a mesh of squares

    Parameters:

    * mesh : :class:`geoist.mesher.SquareMesh` or compatible
        The mesh (a compatible mesh must implement the methods ``get_xs`` and
        ``get_ys``)
    * prop : str
        The physical property of the squares to use as the color scale.
    * cmap : colormap
        Color map to be used. (see pyplot.cm module)
    * vmin, vmax : float
        Saturation values of the colorbar.

    Returns:

    * axes : ``matplitlib.axes``
        The axes element of the plot

    """
    if prop not in mesh.props:
        raise ValueError("Can't plot because 'mesh' doesn't have property '%s'"
                         % (prop))
    xs = mesh.get_xs()
    ys = mesh.get_ys()
    X, Y = numpy.meshgrid(xs, ys)
    V = numpy.reshape(mesh.props[prop], mesh.shape)
    plot = pyplot.pcolor(X, Y, V, cmap=cmap, vmin=vmin, vmax=vmax, picker=True)
    pyplot.xlim(xs.min(), xs.max())
    pyplot.ylim(ys.min(), ys.max())
    return plot 
Example #16
Source File: smokes_friends_cancer.py    From logictensornetworks with MIT License 5 votes vote down vote up
def plt_heatmap(df):
    plt.pcolor(df)
    plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
    plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
    plt.colorbar() 
Example #17
Source File: test_axes.py    From coffeegrindsize with 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 #18
Source File: maxent_objectworld.py    From Inverse-Reinforcement-Learning with MIT License 5 votes vote down vote up
def main(grid_size, discount, n_objects, n_colours, n_trajectories, epochs,
         learning_rate):
    """
    Run maximum entropy inverse reinforcement learning on the objectworld MDP.

    Plots the reward function.

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

    wind = 0.3
    trajectory_length = 8

    ow = objectworld.Objectworld(grid_size, n_objects, n_colours, wind,
                                 discount)
    ground_r = np.array([ow.reward(s) for s in range(ow.n_states)])
    policy = find_policy(ow.n_states, ow.n_actions, ow.transition_probability,
                         ground_r, ow.discount, stochastic=False)
    trajectories = ow.generate_trajectories(n_trajectories,
                                            trajectory_length,
                                            lambda s: policy[s])
    feature_matrix = ow.feature_matrix(discrete=False)
    r = maxent.irl(feature_matrix, ow.n_actions, discount,
        ow.transition_probability, trajectories, epochs, learning_rate)

    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 #19
Source File: maxent_gridworld.py    From Inverse-Reinforcement-Learning with MIT License 5 votes vote down vote up
def main(grid_size, discount, n_trajectories, epochs, learning_rate):
    """
    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 = 0.3
    trajectory_length = 3*grid_size

    gw = gridworld.Gridworld(grid_size, wind, discount)
    trajectories = gw.generate_trajectories(n_trajectories,
                                            trajectory_length,
                                            gw.optimal_policy)
    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)

    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 #20
Source File: NavierStokes.py    From DeepHPMs with 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 #21
Source File: lp_large_gridworld.py    From Inverse-Reinforcement-Learning with MIT License 5 votes vote down vote up
def main(grid_size, discount):
    """
    Run large state space linear programming inverse reinforcement learning on
    the gridworld MDP.

    Plots the reward function.

    grid_size: Grid size. int.
    discount: MDP discount factor. float.
    """

    wind = 0.3
    trajectory_length = 3*grid_size

    gw = gridworld.Gridworld(grid_size, wind, discount)

    ground_r = np.array([gw.reward(s) for s in range(gw.n_states)])
    policy = [gw.optimal_policy_deterministic(s) for s in range(gw.n_states)]

    # Need a value function for each basis function.
    feature_matrix = gw.feature_matrix()
    values = []
    for dim in range(feature_matrix.shape[1]):
        reward = feature_matrix[:, dim]
        values.append(value(policy, gw.n_states, gw.transition_probability,
                            reward, gw.discount))
    values = np.array(values)

    r = linear_irl.large_irl(values, gw.transition_probability,
                        feature_matrix, gw.n_states, gw.n_actions, policy)

    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 #22
Source File: test_axes.py    From coffeegrindsize with 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 #23
Source File: test_backend_pgf.py    From coffeegrindsize with 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 #24
Source File: test_colors.py    From coffeegrindsize with 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 #25
Source File: vis_predictions.py    From spatial-reasoning with MIT License 5 votes vote down vote up
def vis_value_map(pred, targ, save_path, title='prediction', share=True):
    # print 'in vis: ', pred.shape, targ.shape
    dim = int(math.sqrt(pred.size))
    if share:
        vmin = min(pred.min(), targ.min())
        vmax = max(pred.max(), targ.max())
    else:
        vmin = None
        vmax = None

    plt.clf()
    fig, (ax0,ax1) = plt.subplots(1,2,sharey=True)
    heat0 = ax0.pcolor(pred.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet)
    ax0.set_title(title, fontsize=5)
    if not share:
        fig.colorbar(heat0)
    heat1 = ax1.pcolor(targ.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet)
    ax1.invert_yaxis()
    ax1.set_title('target')

    fig.subplots_adjust(right=0.8)
    cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(heat1, cax=cbar_ax)

    # print 'saving to: ', fullpath
    plt.savefig(save_path, bbox_inches='tight')
    plt.close(fig)

    # print pred.shape, targ.shape 
Example #26
Source File: vis_predictions.py    From spatial-reasoning with MIT License 5 votes vote down vote up
def vis_fig(data, save_path, title=None, vmax=None, vmin=None, cmap=cm.jet):
    # print 'in vis: ', pred.shape, targ.shape
    dim = int(math.sqrt(data.size))

    # if share:
    #     vmin = min(pred.min(), targ.min())
    #     vmax = max(pred.max(), targ.max())
    # else:
    #     vmin = None
    #     vmax = None

    plt.clf()
    # fig, (ax0,ax1) = plt.subplots(1,2,sharey=True)
    plt.pcolor(data.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cmap)
    plt.xticks([])
    plt.yticks([])
    # ax0.set_title(title, fontsize=5)
    # if not share:
        # fig.colorbar(heat0)
    # heat1 = ax1.pcolor(targ.reshape(dim,dim), vmin=vmin, vmax=vmax, cmap=cm.jet)
    fig = plt.gcf()
    ax = plt.gca()

    if title:
        ax.set_title(title)
    ax.invert_yaxis()

    fig.set_size_inches(4,4)

    # ax1.invert_yaxis()
    # ax1.set_title('target')

    # fig.subplots_adjust(right=0.8)
    # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    # fig.colorbar(heat1, cax=cbar_ax)

    # print 'saving to: ', fullpath
    plt.savefig(save_path, bbox_inches='tight', pad_inches=0.0)
    plt.close(fig)

    # print pred.shape, targ.shape 
Example #27
Source File: visualization.py    From spatial-reasoning with MIT License 5 votes vote down vote up
def visualize_values(mdp, values, policy, filename, title=None):
    states = mdp.states
    # print states
    plt.clf()
    m = max(states, key=lambda x: x[0])[0] + 1
    n = max(states, key=lambda x: x[1])[1] + 1
    data = np.zeros((m,n))
    for i in range(m):
        for j in range(n):
            state = (i,j)
            if type(values) == dict:
                data[i][j] = values[state]
            else:
                # print values[i][j]
                data[i][j] = values[i][j]
            action = policy[state]
            ## if using all_reachable actions, pick the best one
            if type(action) == tuple:
                action = action[0]
            if action != None:
                x, y, w, h = arrow(i, j, action)
                plt.arrow(x,y,w,h,head_length=0.4,head_width=0.4,fc='k',ec='k')
    heatmap = plt.pcolor(data, cmap=plt.get_cmap('jet'))
    plt.colorbar()
    plt.gca().invert_yaxis()

    if title:
        plt.title(title)
    plt.savefig(filename + '.png')
    # print data 
Example #28
Source File: thinkplot.py    From DataExploration with 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 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 #29
Source File: test_axes.py    From twitter-stock-recommendation with 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 #30
Source File: test_axes.py    From twitter-stock-recommendation with 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)