Python matplotlib.cm 模块,coolwarm() 实例源码

我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用matplotlib.cm.coolwarm()

项目:monogreedy    作者:jinjunqi    | 项目源码 | 文件源码
def draw2dsurface(X, Y, zf):
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    X, Y = np.meshgrid(X, Y)
    Z = X*0
    for i in range(len(X)):
        for j in range(len(X[0])):
            Z[i][j] = zf([X[i][j], Y[i][j]])

    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    ax.set_zlim(np.min(Z.flatten()), np.max(Z.flatten()))

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    # plt.show()
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def trajectory(x, y, z=None, interpolate=None, mark_init=True, mark_end=True,
               force_color_init=None, force_color_end=None, cmap=cm.coolwarm, linewidth=2):
    """
    Wrapper for color_over_time
    :param x:
    :param y:
    :param z:
    :param interpolate:
    :param mark_init:
    :param mark_end:
    :param force_color_init:
    :param force_color_end:
    :param cmap:
    :return:
    """
    color_over_time(x=x, y=y, z=z, interpolate=interpolate, mark_init=mark_init, mark_end=mark_end,
                    force_color_init=force_color_init, force_color_end=force_color_end, cmap=cmap)
项目:pyGPGO    作者:hawk31    | 项目源码 | 文件源码
def plotFranke():
    """
    Plots Franke's function
    """
    x = np.linspace(0, 1, num=1000)
    y = np.linspace(0, 1, num=1000)
    X, Y = np.meshgrid(x, y)
    Z = f(X, Y)

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                           linewidth=0)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
项目:pyGPGO    作者:hawk31    | 项目源码 | 文件源码
def plotPred(gpgo, num=100):
    X = np.linspace(0, 1, num=num)
    Y = np.linspace(0, 1, num=num)
    U = np.zeros((num**2, 2))
    i = 0
    for x in X:
        for y in Y:
            U[i, :] = [x, y]
            i += 1
    z = gpgo.GP.predict(U)[0]
    Z = z.reshape((num, num))
    X, Y = np.meshgrid(X, Y)
    ax = fig.add_subplot(1, 2, 2, projection='3d')
    ax.set_title('Gaussian Process surrogate')
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                           linewidth=0)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    best = gpgo.best
    ax.scatter([best[0]], [best[1]], s=40, marker='x', c='r', label='Sampled point')
    plt.legend(loc='lower right')
    #plt.show()
    return Z
项目:Levenberg_Manquardt    作者:lightforever    | 项目源码 | 文件源码
def initAxes(optimizers):
    interval = functionClass.interval
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    x = np.arange(interval[0][0], interval[0][1], 0.05)
    y = np.arange(interval[1][0], interval[1][1], 0.05)
    X, Y = np.meshgrid(x, y)
    Z = functionClass.getZMeshGrid(X, Y)

    ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    ax.view_init(elev=functionClass.camera[0], azim=functionClass.camera[1])
    plt.legend(
        handles=[mpatches.Patch(color=optimizersColorLookup[optimizer.name], label=optimizer.name) for optimizer in
                 optimizers])

    return fig, ax

# may be list or array
项目:Theano_Tile_Coding    作者:mohammadpz    | 项目源码 | 文件源码
def plot_function(ax, function, text, index, hold=False):
    ax.cla()
    x_0 = np.linspace(0, 7, 100)
    x_1 = np.linspace(0, 7, 100)
    z = np.zeros((100, 100))
    for i in range(100):
        for j in range(100):
            z[j, i] = function(np.array([x_0[i], x_1[j]]))
    X_0, X_1 = np.meshgrid(x_0, x_1)
    ax.plot_surface(X_0, X_1, z, rstride=8, cstride=8, alpha=0.3)
    ax.contourf(X_0, X_1, z, zdir='z', offset=-3, cmap=cm.coolwarm)
    ax.contourf(X_0, X_1, z, zdir='x', offset=-1, cmap=cm.coolwarm)
    ax.contourf(X_0, X_1, z, zdir='y', offset=-1, cmap=cm.coolwarm)
    ax.set_xlim(-1, 8)
    ax.set_ylim(-1, 8)
    ax.set_zlim(-3, 3)
    ax.view_init(45, 45)
    ax.set_title(text)
    if hold:
        plt.show()
    else:
        plt.draw()
        # plt.savefig(str(index) + '.png')
        plt.pause(.0001)
项目:PyGeo    作者:CalvinNeo    | 项目源码 | 文件源码
def paint_surf(a, b, c, points=None):
    fig = pl.figure()
    ax = fig.add_subplot(111, projection='3d')
    X = np.arange(-1, 1, 0.05)
    Y = np.arange(-1, 1, 0.05)
    X, Y = np.meshgrid(X, Y)
    Z = -(X*a + Y*b + c)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    fig.colorbar(surf, shrink=0.5, aspect=5)
    if points != None:
        x1 = points[:, 0]
        y1 = points[:, 1]
        z1 = points[:, 2]
        ax.scatter(x1, y1, z1, c='r')
        pl.show()
项目:PyGeo    作者:CalvinNeo    | 项目源码 | 文件源码
def paint_surfs(surfs, points, xlim=(-1.0, 1.0), ylim=(-1.0, 1.0), zlim=(-1.1, 1.1)):
    fig = pl.figure()
    ax = fig.add_subplot(111, projection='3d')
    for ans, surf_id in zip(surfs, range(len(surfs))):
        a, b, c = ans[0][0], ans[0][1], ans[0][2]
        X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
        Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
        X, Y = np.meshgrid(X, Y)
        Z = -(X*a + Y*b + c)
        # ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
        # fig.colorbar(s, shrink=0.5, aspect=5)
        s = ax.plot_wireframe(X, Y, Z, rstride=15, cstride=15)
        x1 = ans[2][:, 0]
        y1 = ans[2][:, 1]
        z1 = ans[2][:, 2]
        ax.scatter(x1, y1, z1, c='crkgmy'[surf_id])

    ax.set_zlim(zlim[0], zlim[1])
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    # x1 = points[:, 0]
    # y1 = points[:, 1]
    # z1 = points[:, 2]
    # ax.scatter(x1, y1, z1, c='r')
    pl.show()
项目:AIclass    作者:mttk    | 项目源码 | 文件源码
def plot_surface_3d(X, y_actual, NN):
    fig = plt.figure()
    plt.title("Predicted function with marked training samples")
    ax = Axes3D(fig)

    size = X.shape[0]

    ax.view_init(elev=30, azim=70)
    scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)

    x0s = sorted(X[:,0])
    x1s = sorted(X[:,1])

    x0s, x1s = np.meshgrid(x0s, x1s)
    predicted_surface = np.zeros((size, size))

    for i in range(size):
        for j in range(size):
            predicted_surface[i,j] = NN.output(np.array([x0s[i,j], x1s[i,j]]))

    surf = ax.plot_surface(x0s, x1s, predicted_surface, rstride=2, cstride=2, linewidth=0, cmap=cm.coolwarm, alpha=0.5)

    plt.grid()
    plt.show()
项目:AIclass    作者:mttk    | 项目源码 | 文件源码
def plot_surface_3d(X, y_actual, NN):
    fig = plt.figure()
    plt.title("Predicted function with marked training samples")
    ax = Axes3D(fig)

    size = X.shape[0]

    ax.view_init(elev=30, azim=70)
    scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)

    x0s = sorted(X[:,0])
    x1s = sorted(X[:,1])

    x0s, x1s = np.meshgrid(x0s, x1s)
    predicted_surface = np.zeros((size, size))

    for i in range(size):
        for j in range(size):
            predicted_surface[i,j] = NN.output(np.array([x0s[i,j], x1s[i,j]]))

    surf = ax.plot_surface(x0s, x1s, predicted_surface, rstride=2, cstride=2, linewidth=0, cmap=cm.coolwarm, alpha=0.5)

    plt.grid()
    plt.show()
项目:qgis-stereonet    作者:daniel-childs    | 项目源码 | 文件源码
def contourPlot(self):
        fig, ax = mplstereonet.subplots()
        strikes = list()
        dips = list()
        layers = self.iface.legendInterface().layers()
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                iter = layer.selectedFeatures()
                strikeExists = layer.fieldNameIndex('strike')
                ddrExists = layer.fieldNameIndex('ddr')
                dipExists = layer.fieldNameIndex('dip')
                for feature in iter:
                    if strikeExists != -1 and dipExists != -1:
                        strikes.append(feature['strike'])
                        dips.append(feature['dip'])
                    elif ddrExists != -1 and dipExists != -1:
                        strikes.append(feature['ddr']-90)
                        dips.append(feature['dip'])
            else:
                continue
        cax = ax.density_contourf(strikes, dips, measurement='poles',cmap=cm.coolwarm)
        ax.pole(strikes, dips, 'k+', markersize=7)
        ax.grid(True)
#        fig.colorbar(cax)
        plt.show()
项目:MLPractices    作者:carefree0910    | 项目源码 | 文件源码
def visualize2d(self, x=None, y=None, plot_scale=2, plot_precision=0.01):

        x = self._x if x is None else x
        y = self._y if y is None else y

        plot_num = int(1 / plot_precision)

        xf = np.linspace(self._x_min * plot_scale, self._x_max * plot_scale, plot_num)
        yf = np.linspace(self._x_min * plot_scale, self._x_max * plot_scale, plot_num)
        input_x, input_y = np.meshgrid(xf, yf)
        input_xs = np.c_[input_x.ravel(), input_y.ravel()]

        if self._x.shape[1] != 2:
            return
        output_ys_2d = np.argmax(self.predict(input_xs), axis=1).reshape(len(xf), len(yf))
        output_ys_3d = self.predict(input_xs)[..., 0].reshape(len(xf), len(yf))

        xf, yf = np.meshgrid(xf, yf, sparse=True)

        plt.contourf(input_x, input_y, output_ys_2d, cmap=cm.Spectral)
        plt.scatter(x[..., 0], x[..., 1], c=np.argmax(y, axis=1), s=40, cmap=cm.Spectral)
        plt.axis("off")
        plt.show()

        if self._y.shape[1] == 2:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')

            ax.plot_surface(xf, yf, output_ys_3d, cmap=cm.coolwarm, )
            ax.set_xlabel("x")
            ax.set_ylabel("y")
            ax.set_zlabel("z")
            plt.show()
项目:MLPractices    作者:carefree0910    | 项目源码 | 文件源码
def visualize2d(self, x=None, y=None, plot_scale=2, plot_precision=0.01):

        x = self._x if x is None else x
        y = self._y if y is None else y

        plot_num = int(1 / plot_precision)

        xf = np.linspace(self._x_min * plot_scale, self._x_max * plot_scale, plot_num)
        yf = np.linspace(self._x_min * plot_scale, self._x_max * plot_scale, plot_num)
        input_x, input_y = np.meshgrid(xf, yf)
        input_xs = np.c_[input_x.ravel(), input_y.ravel()]

        if self._x.shape[1] != 2:
            return
        output_ys_2d = np.argmax(self.predict(input_xs), axis=1).reshape(len(xf), len(yf))
        output_ys_3d = self.predict(input_xs)[:, 0].reshape(len(xf), len(yf))

        xf, yf = np.meshgrid(xf, yf, sparse=True)

        plt.contourf(input_x, input_y, output_ys_2d, cmap=cm.Spectral)
        plt.scatter(x[:, 0], x[:, 1], c=np.argmax(y, axis=1), s=40, cmap=cm.Spectral)
        plt.axis("off")
        plt.show()

        if self._y.shape[1] == 2:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')

            ax.plot_surface(xf, yf, output_ys_3d, cmap=cm.coolwarm, )
            ax.set_xlabel("x")
            ax.set_ylabel("y")
            ax.set_zlabel("z")
            plt.show()
项目:snn4hrl    作者:florensacc    | 项目源码 | 文件源码
def plot_reward(fig, data_unpickle, color, fig_dir):
    env = data_unpickle['env']
    # retrieve original policy
    poli = data_unpickle['policy']
    mean = poli.get_action(np.array((0, 0)))[1]['mean']
    logstd = poli.get_action(np.array((0, 0)))[1]['log_std']
    # def normal(x): return 1/(np.exp(logstd)*np.sqrt(2*np.pi) )*np.exp(-0.5/np.exp(logstd)**2*(x-mean)**2) 
    ax = fig.gca(projection='3d')
    bound = env.mu[0]*1.2  # bound to plot: 20% more than the good modes
    X = np.arange(-bound, bound, 0.05)
    Y = np.arange(-bound, bound, 0.05)
    X, Y = np.meshgrid(X, Y)
    X_flat = X.reshape((-1, 1))
    Y_flat = Y.reshape((-1, 1))
    XY = np.concatenate((X_flat, Y_flat), axis=1)
    rew = np.array([env.reward_state(xy) for xy in XY]).reshape(np.shape(X))

    surf = ax.plot_surface(X, Y, rew, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    # policy_at0 = [normal(s) for s in x]
    # plt.plot(x,policy_at0,color=color*0.5,label='Policy at 0')
    plt.title('Reward acording to the state')
    fig.colorbar(surf, shrink=0.8)
    # plt.show()
    if fig_dir:
        plt.savefig(os.path.join(fig_dir, 'Reward_function'))
    else:
        print("No directory for saving plots")


# Plot learning curve
项目:pyGPGO    作者:hawk31    | 项目源码 | 文件源码
def plotFranke():
    x = np.linspace(0, 1, num=1000)
    y = np.linspace(0, 1, num=1000)
    X, Y = np.meshgrid(x, y)
    Z = f(X, Y)
    ax = fig.add_subplot(1, 2, 1, projection='3d')
    ax.set_title('Original function')

    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                           linewidth=0)
    fig.colorbar(surf, shrink=0.5, aspect=5)
项目:simple-linear-regression    作者:williamd4112    | 项目源码 | 文件源码
def plot_3d(model, phi, x_min, x_max, y_min, y_max, z_min, z_max, filename=None):
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    X = np.arange(x_min, x_max, 5)
    Y = np.arange(y_min, y_max, 5)
    X, Y = np.meshgrid(X, Y)

    x, y = np.reshape(X, len(X)**2), np.reshape(Y, len(Y)**2) 
    Z = model(np.matrix(phi(np.array([x, y], dtype=np.float32).T)))

    Z = np.reshape(Z, [len(X), len(X)])    

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False, shade=True)

    # Customize the z axis.
    ax.set_zlim(z_min, z_max)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def plot_surface(self):
        fig = plt.figure(figsize = (8,8))
        ax = fig.gca(projection='3d')
        X, Y = np.meshgrid(np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)), np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)))
        surf = ax.plot_surface(X, Y, self.lattice_in, rstride=1, cstride=1,cmap = cm.coolwarm,
                       linewidth=0, antialiased=False)
        ax.set_zlim(-1.01, 1.01)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
        fig.colorbar(surf, shrink=0.5, aspect=10)
项目:bates_galaxies_lab    作者:aleksds    | 项目源码 | 文件源码
def daplot(quantity, qmin, qmax):
        ax.set_xlim(0, size)
        ax.set_ylim(0, size)
        ax.set_xticklabels(())
        ax.set_yticklabels(())
        plt.imshow(quantity, origin='lower', interpolation='nearest',
                   norm=colors.LogNorm(vmin=qmin, vmax=qmax), cmap=cm.coolwarm)
        cbar = plt.colorbar()
        cbar.ax.tick_params(labelsize=14)

# minimum and maximum emission-line fluxes for plot ranges
项目:bates_galaxies_lab    作者:aleksds    | 项目源码 | 文件源码
def daplot(quantity, qmin, qmax):
        ax.set_xlim(0, size)
        ax.set_ylim(0, size)
        ax.set_xticklabels(())
        ax.set_yticklabels(())
        plt.imshow(quantity, origin='lower', interpolation='nearest',
                   norm=colors.LogNorm(vmin=qmin, vmax=qmax), cmap=cm.coolwarm)
        plt.colorbar()

# minimum and maximum emission-line fluxes for plot ranges
项目:bates_galaxies_lab    作者:aleksds    | 项目源码 | 文件源码
def daplot(quantity, qmin, qmax):
        ax.set_xlim(0, size)
        ax.set_ylim(0, size)
        ax.set_xticklabels(())
        ax.set_yticklabels(())
        plt.imshow(quantity, origin='lower', interpolation='nearest',
                   norm=colors.LogNorm(vmin=qmin, vmax=qmax), cmap=cm.coolwarm)
        plt.colorbar()

# minimum and maximum emission-line fluxes for plot ranges
项目:kaleidoscope    作者:michaelchu    | 项目源码 | 文件源码
def plot(self, exp):
        """
        Plot this OptionSeries with a surface plot for an expiration cycle.

        :param exp: The expiration to plot for
        :return:
        """

        data = self.option_chains[exp]

        # reset dataframe labels and column names to be numeric
        data.columns = [i for i in range(data.shape[1])]
        data.reset_index(inplace=True)

        # drop either symbol or spread_symbol columns depending on strategy
        data.drop('symbol' if 'spread_symbol' not in data else 'spread_symbol', axis=1, inplace=True)

        x = data.columns
        y = data.index

        X, Y = np.meshgrid(x, y)
        Z = data

        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0)

        plt.show()
项目:computationalphysics_N2014301020131    作者:Nucleus2014    | 项目源码 | 文件源码
def plot_3d(self,ax,x1,x2,y1,y2):   # give 3d plot the potential
        self.x=linspace(x1,x2,self.n)
        self.y=linspace(y2,y1,self.n)
        self.x,self.y=meshgrid(self.x,self.y)
        self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
        ax.set_xlim(x1,x2)
        ax.set_ylim(y1,y2)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
        ax.set_xlabel('x (m)',fontsize=14)
        ax.set_ylabel('y (m)',fontsize=14)
        ax.set_zlabel('Electric potential (V)',fontsize=14)
        ax.set_title('Potential near capacitor',fontsize=18)
项目:computationalphysics_N2014301020131    作者:Nucleus2014    | 项目源码 | 文件源码
def plot_3d(self,ax,x1,x2,y1,y2):   # give 3d plot the potential
        self.x=linspace(x1,x2,self.n)
        self.y=linspace(y2,y1,self.n)
        self.x,self.y=meshgrid(self.x,self.y)
        self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
        ax.set_xlim(x1,x2)
        ax.set_ylim(y1,y2)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
        ax.set_xlabel('x (m)',fontsize=14)
        ax.set_ylabel('y (m)',fontsize=14)
        ax.set_zlabel('Electric potential (V)',fontsize=14)
        ax.set_title('Potential near capacitor',fontsize=18)
项目:computationalphysics_N2014301020131    作者:Nucleus2014    | 项目源码 | 文件源码
def plot_3d(self,ax,x1,x2,y1,y2):       # give 3d plot the potential
        self.x=linspace(x1,x2,self.n)
        self.y=linspace(y2,y1,self.n)
        self.x,self.y=meshgrid(self.x,self.y)
        self.surf=ax.plot_surface(self.x,self.y,self.V, rstride=1, cstride=1, cmap=cm.coolwarm)
        ax.set_xlim(x1,x2)
        ax.set_ylim(y1,y2)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
        ax.set_xlabel('x (m)',fontsize=14)
        ax.set_ylabel('y (m)',fontsize=14)
        ax.set_zlabel('Electric potential (V)',fontsize=14)
        ax.set_title('Potential near capacitor',fontsize=18)
项目:AutoEncoder    作者:np2lkoo    | 项目源码 | 文件源码
def report_w3d(self, my_ae):
        for period in range(np.int(np.log2(my_ae.epoch_limit) + 1)):
            targetW = my_ae.get_W1(period)
            x = range(27)
            y = range(27)

        ax3d = plt.subplot(self.gs[period, 2])
        X, Y = np.meshgrid(x, y)
        Z = targetW[2][X + (784 - 28) - Y * 28]
        fig = plt.figure()
        #ax = Axes3D(fig)
        ax = fig.gca(projection='3d')
        # ax.plot_wireframe(X,Y,Z)
        plt.cool()
        cset = ax.contourf(X, Y, Z, zdir='z', offset=-4, cmap=cm.coolwarm)
        cset = ax.contourf(X, Y, Z, zdir='x', offset=-1, cmap=cm.cool)
        cset = ax.contourf(X, Y, Z, zdir='y', offset=-1, cmap=cm.cool)
        ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.3)
        # ax.contourf3D(X,Y,Z)
        # surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        #                       linewidth=0, antialiased=False)
        # fig.colorbar(surf, shrink=0.5, aspect=5)
        ax.view_init(20, 30)
        ax.set_xlabel('X')
        ax.set_xlim(0, 27)
        ax.set_ylabel('Y')
        ax.set_ylim(0, 27)
        ax.set_zlabel('Z')
        ax.set_zlim(-4, 3)
        plt.show()
项目:snn4hrl    作者:florensacc    | 项目源码 | 文件源码
def plot_snn_at0(fig, data_unpickle, itr='last', color=(1, 0.1, 0.1), fig_dir=None):
    # recover the policy
    poli = data_unpickle['policy']
    env = data_unpickle['env']
    # range to plot it
    bound = env.mu[0]*1.5
    num_bins = 600
    step = (2. * bound) / num_bins
    samples = (num_bins) ** 2
    x = np.arange(-bound, bound + step, step)
    y = np.arange(-bound, bound + step, step)
    x, y = np.meshgrid(x, y)
    p_xy = np.zeros_like(x)
    for _ in range(samples):
        a = poli.get_action(np.array((0, 0)))[0]
        idx_x = int(np.floor(a[0] / step) + bound / step)
        idx_y = int(np.floor(a[1] / step) + bound / step)
        # find the coord of the action in the grid
        if idx_x >= 0 and idx_x < np.shape(x)[1]:
            px = idx_x
        elif idx_x < 0:
            px = 0
        else:
            px = np.shape(x)[1] - 1
        # same for y
        if idx_y >= 0 and idx_y < np.shape(y)[0]:
            py = idx_y
        elif idx_y < 0:
            py = 0
        else:
            py = np.shape(y)[0] - 1
        p_xy[px, py] += 1

    ax = fig.gca(projection='3d')
    p_xy = p_xy / float(samples)
    surf = ax.plot_surface(y, x, p_xy, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    plt.title('Policy distribution at 0 after {} iter'.format(itr))
    fig.colorbar(surf, shrink=0.8)
    # plt.xlabel('next state')
    # plt.ylabel('probability mass')
    if fig_dir:
        plt.savefig(os.path.join(fig_dir, 'MC_policy_learned_at0_iter{}'.format(itr)))
    else:
        print("No directory for saving plots")
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def color_over_trajectories(x, y, c=None, mark_init=True, mark_end=True, cmap=cm.coolwarm, linewidth=2):

    # Determine number of curves
    # niceFigure()
    x = np.squeeze(x)
    y = np.squeeze(y)
    if type(x).__module__ == np.__name__:
        if x.ndim is 1:
            n_x_curves = 1
        else:
            n_x_curves = x.shape[0]
    if isinstance(x, list):
        n_x_curves = len(x)  # already a list
    if type(y).__module__ == np.__name__:
        if y.ndim is 1:
            n_y_curves = 1
        else:
            n_y_curves = y.shape[0]
    if isinstance(y, list):
        n_y_curves = len(y)  # already a list

    assert (n_y_curves == n_x_curves) or (n_x_curves == 1) or (n_y_curves == 1)
    n_curves = max(n_x_curves, n_y_curves)
    assert (n_curves >= 1)

    # Convert everything to list (if not already)
    if type(x).__module__ == np.__name__:
        if x.ndim is 1:
            x = [x] * n_curves  # Single trajectory
        else:
            list(x)  # Multiple trajectories, decompose into a list
    if type(y).__module__ == np.__name__:
        if y.ndim is 1:
            y = [y] * n_curves  # Single trajectory
        else:
            list(y)  # Multiple trajectories, decompose into a list

    if c is None:
        c = np.linspace(0, 1, n_curves)  # your "time" variable
    else:
        # TODO: Normalize c to 0-1
        pass
    colors = cmap(c)

    niceFigure()
    fig = plt.figure(figsize=(10, 6))
    ax = fig.add_subplot(1, 1, 1)
    for i in range(n_curves):
        plt.plot(x[i], y[i], color=colors[i], linewidth=linewidth)

        if mark_init:
            plt.plot(x[i][0], y[i][0], 'o', color=colors[i])
        if mark_end:
            plt.plot(x[i][-1], y[i][-1], 'o', color=colors[i])

    return fig
项目:bbho    作者:DarkElement75    | 项目源码 | 文件源码
def graph_output(plot_2d_results, plot_3d_results, bbf_evaluation_i, bbf_evaluation_n, domain_x, domain_y, detail_n, test_means, bbf_inputs, bbf_evaluations, val1, val2):

  #Set the filename
  fname = "results/%02d" % bbf_evaluation_i

  #Plot our updates
  if plot_2d_results:
      plt.plot(domain_x, test_means)
      #plt.plot(domain_x, test_variances, 'r')
      #plt.plot(bbf_inputs, bbf_evaluations, 'bo')
      plt.scatter(bbf_inputs, bbf_evaluations, marker='o', c='b', s=100.0, label="Function Evaluations")
      plt.plot(domain_x, val1, 'r')
      plt.plot(domain_x, val2, 'r')
      #plt.plot(domain_x, bbf(domain_x), 'y')
      plt.savefig("%s.jpg" % fname, dpi=None, facecolor='w', edgecolor='w',
          orientation='portrait', papertype=None, format=None,
          transparent=False, bbox_inches='tight', pad_inches=0.1,
          frameon=None)
      plt.xlabel("X-Axis")
      plt.ylabel("Y-Axis")

      plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.)
      plt.axis([0, 10, 0, 2])
      #plt.show()
      plt.gcf().clear()

  elif plot_3d_results:
      #So we only render on the last one(just erase this if you want all of them)
      if bbf_evaluation_i == bbf_evaluation_n-1:
          fig = plt.figure()
          ax = fig.add_subplot(111, projection='3d')
          #X & Y have to be matrices of all vertices
          #Z has to be matrix of outputs
          #Convert our vectors to compatible matrix counterparts
          Y = np.array([[i] for i in domain_y])

          X = np.tile(domain_x, (detail_n, 1))
          Y = np.tile(Y, (1, detail_n))

          #This ones easy, just reshape
          Z1 = test_means.reshape(detail_n, detail_n)
          #Z2 = test_variances.reshape(detail_n, detail_n)
          Z3 = (val1).reshape(detail_n, detail_n)
          Z4 = (val2).reshape(detail_n, detail_n)


          ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, cmap=cm.coolwarm)
          #ax.plot_wireframe(X, Y, Z2, rstride=1, cstride=1)
          ax.plot_wireframe(X, Y, Z3, rstride=1, cstride=1)
          ax.plot_wireframe(X, Y, Z4, rstride=1, cstride=1)
          plt.savefig("%s.jpg" % fname, dpi=None, facecolor='w', edgecolor='w',
              orientation='portrait', papertype=None, format=None,
              transparent=False, bbox_inches='tight', pad_inches=0.1,
              frameon=None)

          plt.gcf().clear()
          #plt.show()
项目:geonum    作者:jgliss    | 项目源码 | 文件源码
def draw_topo_old(self, insert_colorbar=False, include_seabed=True,
                    max_grid_points=500, cmap_div=colormaps.coolwarm,
                    cmap_seq=colormaps.Oranges, alpha=0.5, ax=None):
        """Draw topography into map

        :param bool insert_colorbar: draws a colorbar for altitude
            range (default: False)
        :param bool include_seabed: include seabed topography 
            (default: True)
        :param int max_grid_points: resolution of displayed topo data 
            points (makes it faster in interactive mode, default: 500)
        :param str cmap_div: name of a diverging colormap (this one is 
            used if :arg:`include_seabed` is True, and the cmap is shifted 
            such , that white colors correspond to sea level altitude, 
            default: "coolwarm")
        :param str cmap_seq: name of a sequential colormap (this one is 
            used if :arg:`include_seabed` is False, default: "Oranges")
        :param float alpha: Alpha value (transparency) of plotted 
            topography
        :param ax: matplotlib axes object
        """
        try:  
            if ax is None:
                ax = self.ax
            if ax is None:
                fig, ax = subplots(1, 1, figsize=(16,10))
                self.ax = ax

            x, y, z, z_min, z_max, z_order =\
                self._prep_topo_data(grid_points=max_grid_points)

            if z_min > 0:
                include_seabed = 1

            z_step = (z_max - z_min) / 1000. 

            if include_seabed:
                levels_filled = arange(z_min, z_max + z_step, z_step)
            else:
                levels_filled = arange(0, z_max + 1, z_step)
            if levels_filled[0] < 0:          
                shifted_cmap = shifted_color_map(z_min, z_max, cmap_div)

                cs2 = ax.contourf(x, y, z, levels_filled, cmap=shifted_cmap,
                                  extend="both", alpha=alpha)

            elif levels_filled[0] >= 0:        
                print "HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEERE"
                cs2 = ax.contourf(x, y, z, levels_filled, cmap=cmap_seq,
                                  alpha=1.0, extend="min")
                self.contour_filled = cs2

            if insert_colorbar:              
                self.insert_colorbar("topo", cs2, label="Altitude [m]")

        except Exception as e:
            raise
            msg=("Could not draw topography in high res, using default "
                 "etopo() instead...")
            print msg + repr(e)
            self.etopo()
项目:rswarp    作者:radiasoft    | 项目源码 | 文件源码
def __init__(self, ax, ax_colorbar, scraper, top, w3d):
        """
        Plots density of scraped particles on conducting objects.

        Can evaluate density on each surface of a Box or ZPlane separately and produce shaded density plots.
        To run automatically: call an initialized PlotDensity object.

        Warning: Only Box and ZPlane are supported at this time. Other conductor shapes will not be evaluated correctly.
                Only for 2D XZ simulations at this time.

        Args:
            ax: Matplotlib axes object for surface density plots.
            ax_colorbar: Matplotlib axes object for colorbar.
            scraper: Warp ParticleScraper object. Only used to acquire conductor positions and dimensions.
            top: Warp top object.
            w3d: Warp w3d object.

        Useful attributes:
            ax: Matplotilb axes object for density plots
            ax_colorbar: Matplotlib axes object for colorbar
            scraper: Warp ParticleScraper object
            zplost: Array of z-positions of lost particles. Defaults to top.zplost.
            xplost: Array of x-positions of lost particles. Defaults to top.xplost.
            dz, dx: z and x widths used to gate on particles collected by conductor side.
                Defaults to w3d.dz and w3d.dx
            scale: Set scale of x and z units. Defaults to 1e6 (units of microns).
            cmap: matplotlib.cm colormap. Defaults to coolwarm.
            normalization: matplotlib.colors normalization function. Defaults to Normalize (linear normalization).
        """

        self.ax = ax
        self.ax_colorbar = ax_colorbar
        self.scraper = scraper
        self.top = top
        self.w3d = w3d

        self.gated_ids = {}
        self.dx = w3d.dx
        self.dz = w3d.dz
        self.scale = 1e6
        # categorize the number lost to avoid padded values at end of array
        self.numlost = top.npslost[0]
        assert self.numlost > 1, "No particles lost in simulation. Nothing to plot."

        self.zplost = self.top.zplost[:self.numlost]
        self.xplost = self.top.xplost[:self.numlost]

        self.cmap = cm.coolwarm
        self.normalization = Normalize
        self.cmap_normalization = None