Python matplotlib.cm.coolwarm() Examples

The following are 30 code examples for showing how to use matplotlib.cm.coolwarm(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module matplotlib.cm , or try the search function .

Example 1
Project: NiaPy   Author: NiaOrg   File: benchmark.py    License: MIT License 6 votes vote down vote up
def plot3d(self, scale=0.32):
		r"""Plot 3d scatter plot of benchmark function.

		Args:
			scale (float): Scale factor for points.
		"""
		fig = plt.figure()
		ax = Axes3D(fig)
		func = self.function()
		Xr, Yr = arange(self.Lower, self.Upper, scale), arange(self.Lower, self.Upper, scale)
		X, Y = meshgrid(Xr, Yr)
		Z = vectorize(self.__2dfun)(X, Y, func)
		ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
		ax.contourf(X, Y, Z, zdir='z', offset=-10, cmap=cm.coolwarm)
		ax.set_xlabel('X')
		ax.set_ylabel('Y')
		ax.set_zlabel('Z')
		plt.show()

# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3 
Example 2
Project: pyGPGO   Author: josejimenezluna   File: franke.py    License: MIT License 6 votes vote down vote up
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() 
Example 3
Project: pyGPGO   Author: josejimenezluna   File: gif_gen.py    License: MIT License 6 votes vote down vote up
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 
Example 4
Project: Image-Restoration   Author: limingwu8   File: deforme.py    License: MIT License 6 votes vote down vote up
def plot_surface(x,y,z):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    # Customize the z axis.
    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)
    if save_info:
        fig.tight_layout()
        fig.savefig('./gaussian'+ str(idx) + '.png')
    plt.show() 
Example 5
Project: pyray   Author: ryu577   File: lagrange.py    License: MIT License 6 votes vote down vote up
def three_d_grid():
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Make data.
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = (X**3 + Y**3)
    Z = R

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

    # Customize the z axis.
    #ax.set_zlim(-1.01, 1.01)
    #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() 
Example 6
Project: python-urbanPlanning   Author: richieBao   File: LST.py    License: MIT License 6 votes vote down vote up
def ThrShow(self,data):        
        font1 = {'family' : 'STXihei',
         'weight' : 'normal',
         'size'   : 50,
         }
        fig, ax = plt.subplots(subplot_kw=dict(projection='3d'),figsize=(50,20))
        ls = LightSource(data.shape[0], data.shape[1])
        rgb = ls.shade(data, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
        x=np.array([list(range(data.shape[0]))]*data.shape[1])
        print(x.shape,x.T.shape,data.shape)
        surf = ax.plot_surface(x, x.T, data, rstride=1, cstride=1, facecolors=rgb,linewidth=0, antialiased=False, shade=False,alpha=0.3)
        fig.colorbar(surf,shrink=0.5,aspect=5)
        cset = ax.contour(x, x.T, data, zdir='z', offset=37, cmap=cm.coolwarm)
        cset = ax.contour(x, x.T, data, zdir='x', offset=-30, cmap=cm.coolwarm)
        cset = ax.contour(x, x.T, data, zdir='y', offset=-30, cmap=cm.coolwarm)
        plt.show() 
Example 7
Project: crappy   Author: LaboratoireMecaniqueLille   File: drawing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def update(self,data):
    self.txt.set_text(self.text%data[self.label])
    self.dot.set_color(cm.coolwarm((data[self.label]-self.low)/self.amp)) 
Example 8
Project: crappy   Author: LaboratoireMecaniqueLille   File: drawing.py    License: GNU General Public License v2.0 5 votes vote down vote up
def prepare(self):
    plt.switch_backend(self.backend)
    self.fig, self.ax = plt.subplots(figsize=self.window_size)
    image = self.ax.imshow(plt.imread(self.image), cmap=cm.coolwarm)
    image.set_clim(-0.5, 1)
    cbar = self.fig.colorbar(image, ticks=[-0.5, 1], fraction=0.061,
        orientation='horizontal', pad=0.04)
    cbar.set_label('Temperatures(C)')
    cbar.ax.set_xticklabels(self.crange)
    self.ax.set_title(self.title)
    self.ax.set_axis_off()

    self.elements = []
    for d in self.draw:
      self.elements.append(elements[d['type']](self,**d)) 
Example 9
Project: pyGPGO   Author: josejimenezluna   File: gif_gen.py    License: MIT License 5 votes vote down vote up
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) 
Example 10
Project: deep-learning-samples   Author: eliben   File: simple_linear_regression.py    License: The Unlicense 5 votes vote down vote up
def plot_cost_3D(x, y, costfunc, mb_history=None):
    """Plot cost as 3D and contour.

    x, y: arrays of data.
    costfunc: cost function with signature like compute_cost.
    mb_history:
        if provided, it's a sequence of (m, b) pairs that are added as
        crosshairs markers on top of the contour plot.
    """
    lim = 10.0
    N = 250
    ms = np.linspace(-lim, lim, N)
    bs = np.linspace(-lim, lim, N)
    cost = np.zeros((N, N))
    for m_idx in range(N):
        for b_idx in range(N):
            cost[m_idx, b_idx] = costfunc(x, y, ms[m_idx], bs[b_idx])
    # Configure 3D plot.
    fig = plt.figure()
    fig.set_tight_layout(True)
    ax1 = fig.add_subplot(1, 2, 1, projection='3d')
    ax1.set_xlabel('b')
    ax1.set_ylabel('m')
    msgrid, bsgrid = np.meshgrid(ms, bs)
    surf = ax1.plot_surface(msgrid, bsgrid, cost, cmap=cm.coolwarm)

    # Configure contour plot.
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.contour(msgrid, bsgrid, cost)
    ax2.set_xlabel('b')
    ax2.set_ylabel('m')

    if mb_history:
        ms, bs = zip(*mb_history)
        plt.plot(bs, ms, 'rx', mew=3, ms=5)

    plt.show() 
Example 11
Project: pySDC   Author: Parallel-in-Time   File: HookClass.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post_step(self, status):
        """
        Overwrite standard dump per step

        Args:
            status: status object per step
        """
        super(plot_solution,self).post_step(status)

        #yplot = self.level.uend.values
        #xx    = self.level.prob.xx
        #zz    = self.level.prob.zz
        #self.fig.clear()
        #plt.plot( xx[:,0], yplot[2,:,0])
        #plt.ylim([-1.1, 1.1])
        #plt.show(block=False)
        #plt.pause(0.00001)        
          
        if True:
          yplot = self.level.uend.values
          xx    = self.level.prob.xx
          zz    = self.level.prob.zz
          self.fig.clear()
          CS = plt.contourf(xx, zz, yplot[2,:,:], rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
          cbar = plt.colorbar(CS)
          plt.axes().set_xlim(xmin = self.level.prob.x_bounds[0], xmax = self.level.prob.x_bounds[1])
          plt.axes().set_ylim(ymin = self.level.prob.z_bounds[0], ymax = self.level.prob.z_bounds[1])
          plt.axes().set_aspect('equal')
          plt.xlabel('x')
          plt.ylabel('z')
          #plt.tight_layout()
          plt.show(block=False)
          plt.pause(0.00001)

        return None 
Example 12
Project: pySDC   Author: Parallel-in-Time   File: HookClass.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post_step(self, status):
        """
        Overwrite standard dump per step

        Args:
            status: status object per step
        """
        super(plot_solution,self).post_step(status)

        if False:
          yplot = self.level.uend.values
          xx    = self.level.prob.xc
          yy    = self.level.prob.yc
          self.fig.clear()
          plt.plot( xx[:,0], yplot[0,:,0])
          plt.ylim([-1.0, 1.0])
          plt.show(block=False)
          plt.pause(0.00001)        

            
        if True:
          yplot = self.level.uend.values
          xx    = self.level.prob.xc
          zz    = self.level.prob.yc
          self.fig.clear()
          CS = plt.contourf(xx, zz, yplot[0,:,:], rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
          cbar = plt.colorbar(CS)
          #plt.axes().set_xlim(xmin = self.level.prob.x_b[0], xmax = self.level.prob.x_b[1])
          #plt.axes().set_ylim(ymin = self.level.prob.z_b[0], ymax = self.level.prob.z_b[1])
          #plt.axes().set_aspect('equal')
          plt.xlabel('x')
          plt.ylabel('z')
          #plt.tight_layout()
          plt.show(block=False)
          plt.pause(0.00001)

        return None 
Example 13
Project: copula-py   Author: stochasticresearch   File: plot_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot_3d(X,Y,Z, titleStr):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    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)
    plt.xlabel('U1')
    plt.ylabel('U2')
    plt.title(titleStr)
    plt.show() 
Example 14
Project: xrt   Author: kklmn   File: read_NOM_maps.py    License: MIT License 5 votes vote down vote up
def plot_NOM_3D(fname):
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    xL, yL, zL = np.loadtxt(fname+'.dat', unpack=True)
    nX = (yL == yL[0]).sum()
    nY = (xL == xL[0]).sum()
    x = xL.reshape((nY, nX))
    y = yL.reshape((nY, nX))
    z = zL.reshape((nY, nX))
    x1D = xL[:nX]
    y1D = yL[::nX]
#    z += z[::-1, :]
    zmax = abs(z).max()

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False, alpha=0.5)
    ax.set_zlim(-zmax, zmax)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

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

    splineZ = ndimage.spline_filter(z.T)
    nrays = 1e3
    xnew = np.random.uniform(x1D[0], x1D[-1], nrays)
    ynew = np.random.uniform(y1D[0], y1D[-1], nrays)
    coords = np.array([(xnew-x1D[0]) / (x1D[-1]-x1D[0]) * (nX-1),
                       (ynew-y1D[0]) / (y1D[-1]-y1D[0]) * (nY-1)])
    znew = ndimage.map_coordinates(splineZ, coords, prefilter=True)
    ax.scatter(xnew, ynew, znew, c=znew, marker='o', color='gray', s=50,
               cmap=cm.coolwarm)

    fig.savefig(fname+'_3d.png')
    plt.show() 
Example 15
Project: incubator-sdap-nexus   Author: apache   File: lat_hof_moeller.py    License: Apache License 2.0 5 votes vote down vote up
def createHoffmueller(data, coordSeries, timeSeries, coordName, title, interpolate='nearest'):

    cmap = cm.coolwarm
    # ls = LightSource(315, 45)
    # rgb = ls.shade(data, cmap)

    fig, ax = plt.subplots()
    fig.set_size_inches(11.0, 8.5)
    cax = ax.imshow(data, interpolation=interpolate, cmap=cmap)

    def yFormatter(y, pos):
        if y < len(coordSeries):
            return "%s $^\circ$" % (int(coordSeries[int(y)] * 100.0) / 100.)
        else:
            return ""

    def xFormatter(x, pos):
        if x < len(timeSeries):
            return timeSeries[int(x)].strftime('%b %Y')
        else:
            return ""

    ax.xaxis.set_major_formatter(FuncFormatter(xFormatter))
    ax.yaxis.set_major_formatter(FuncFormatter(yFormatter))

    ax.set_title(title)
    ax.set_ylabel(coordName)
    ax.set_xlabel('Date')

    fig.colorbar(cax)
    fig.autofmt_xdate()

    plt.show() 
Example 16
Project: incubator-sdap-nexus   Author: apache   File: lon_hof_moeller.py    License: Apache License 2.0 5 votes vote down vote up
def createHoffmueller(data, coordSeries, timeSeries, coordName, title, interpolate='nearest'):

    cmap = cm.coolwarm
    # ls = LightSource(315, 45)
    # rgb = ls.shade(data, cmap)

    fig, ax = plt.subplots()
    fig.set_size_inches(11.0, 8.5)
    cax = ax.imshow(data, interpolation=interpolate, cmap=cmap)

    def yFormatter(y, pos):
        if y < len(coordSeries):
            return "%s $^\circ$" % (int(coordSeries[int(y)] * 100.0) / 100.)
        else:
            return ""

    def xFormatter(x, pos):
        if x < len(timeSeries):
            return timeSeries[int(x)].strftime('%b %Y')
        else:
            return ""

    ax.xaxis.set_major_formatter(FuncFormatter(xFormatter))
    ax.yaxis.set_major_formatter(FuncFormatter(yFormatter))

    ax.set_title(title)
    ax.set_ylabel(coordName)
    ax.set_xlabel('Date')

    fig.colorbar(cax)
    fig.autofmt_xdate()

    plt.show() 
Example 17
Project: incubator-sdap-nexus   Author: apache   File: HofMoellerSpark.py    License: Apache License 2.0 5 votes vote down vote up
def createHoffmueller(self, data, coordSeries, timeSeries, coordName, title, interpolate='nearest'):
        cmap = cm.coolwarm
        # ls = LightSource(315, 45)
        # rgb = ls.shade(data, cmap)

        fig, ax = plt.subplots()
        fig.set_size_inches(11.0, 8.5)
        cax = ax.imshow(data, interpolation=interpolate, cmap=cmap)

        def yFormatter(y, pos):
            if y < len(coordSeries):
                return "%s $^\circ$" % (int(coordSeries[int(y)] * 100.0) / 100.)
            else:
                return ""

        def xFormatter(x, pos):
            if x < len(timeSeries):
                return timeSeries[int(x)].strftime('%b %Y')
            else:
                return ""

        ax.xaxis.set_major_formatter(FuncFormatter(xFormatter))
        ax.yaxis.set_major_formatter(FuncFormatter(yFormatter))

        ax.set_title(title)
        ax.set_ylabel(coordName)
        ax.set_xlabel('Date')

        fig.colorbar(cax)
        fig.autofmt_xdate()

        labels = ['point {0}'.format(i + 1) for i in range(len(data))]
        # plugins.connect(fig, plugins.MousePosition(fontsize=14))
        tooltip = mpld3.plugins.PointLabelTooltip(cax, labels=labels)

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
Example 18
Project: incubator-sdap-nexus   Author: apache   File: plotting.py    License: Apache License 2.0 5 votes vote down vote up
def createHoffmueller(data, coordSeries, timeSeries, coordName, title, interpolate='nearest'):
    cmap = cm.coolwarm
    # ls = LightSource(315, 45)
    # rgb = ls.shade(data, cmap)

    fig, ax = plt.subplots()
    fig.set_size_inches(11.0, 8.5)
    cax = ax.imshow(data, interpolation=interpolate, cmap=cmap)

    def yFormatter(y, pos):
        if y < len(coordSeries):
            return "%s $^\circ$" % (int(coordSeries[int(y)] * 100.0) / 100.)
        else:
            return ""

    def xFormatter(x, pos):
        if x < len(timeSeries):
            return timeSeries[int(x)].strftime('%b %Y')
        else:
            return ""

    ax.xaxis.set_major_formatter(FuncFormatter(xFormatter))
    ax.yaxis.set_major_formatter(FuncFormatter(yFormatter))

    ax.set_title(title)
    ax.set_ylabel(coordName)
    ax.set_xlabel('Date')

    fig.colorbar(cax)
    fig.autofmt_xdate()

    labels = ['point {0}'.format(i + 1) for i in range(len(data))]
    # plugins.connect(fig, plugins.MousePosition(fontsize=14))
    tooltip = mpld3.plugins.PointLabelTooltip(cax, labels=labels)
    mpld3.plugins.connect(fig, tooltip)
    mpld3.show()
    # sio = StringIO()
    # plt.savefig(sio, format='png')
    # return sio.getvalue() 
Example 19
Project: Hopfield-Network   Author: takyamamoto   File: network.py    License: MIT License 5 votes vote down vote up
def plot_weights(self):
        plt.figure(figsize=(6, 5))
        w_mat = plt.imshow(self.W, cmap=cm.coolwarm)
        plt.colorbar(w_mat)
        plt.title("Network Weights")
        plt.tight_layout()
        plt.savefig("weights.png")
        plt.show() 
Example 20
Project: mushroom-rl   Author: MushroomRL   File: pendulum_dpg.py    License: MIT License 5 votes vote down vote up
def __init__(self, V, mu, low, high, phi, psi):
        plt.ion()

        self._V = V
        self._mu = mu
        self._phi = phi
        self._psi = psi

        fig = plt.figure(figsize=(10, 5))
        ax1 = fig.add_subplot(1, 2, 1)
        ax2 = fig.add_subplot(1, 2, 2)

        self._theta = np.linspace(low[0], high[0], 100)
        self._omega = np.linspace(low[1], high[1], 100)

        vv, mm = self._compute_data()

        ext = [low[0], high[0],
               low[1], high[1]]

        ax1.set_title('V')
        im1 = ax1.imshow(vv, cmap=cm.coolwarm, extent=ext, aspect='auto')
        fig.colorbar(im1, ax=ax1)

        ax2.set_title('mean')
        im2 = ax2.imshow(mm, cmap=cm.coolwarm, extent=ext, aspect='auto')
        fig.colorbar(im2, ax=ax2)

        self._im = [im1, im2]

        self._counter = 0

        plt.draw()
        plt.pause(0.1) 
Example 21
Project: mushroom-rl   Author: MushroomRL   File: pendulum_ac.py    License: MIT License 5 votes vote down vote up
def __init__(self, V, mu, std, low, high, phi, psi):
        plt.ion()

        self._V = V
        self._mu = mu
        self._std = std
        self._phi = phi
        self._psi = psi

        fig = plt.figure(figsize=(15, 5))
        ax1 = fig.add_subplot(1, 3, 1)
        ax2 = fig.add_subplot(1, 3, 2)
        ax3 = fig.add_subplot(1, 3, 3)

        self._theta = np.linspace(low[0], high[0], 100)
        self._omega = np.linspace(low[1], high[1], 100)

        vv, mm, ss = self._compute_data()

        ext = [low[0], high[0],
               low[1], high[1]]

        ax1.set_title('V')
        im1 = ax1.imshow(vv, cmap=cm.coolwarm, extent=ext, aspect='auto')
        fig.colorbar(im1, ax=ax1)

        ax2.set_title('mean')
        im2 = ax2.imshow(mm, cmap=cm.coolwarm, extent=ext, aspect='auto')
        fig.colorbar(im2, ax=ax2)

        ax3.set_title('sigma')
        im3 = ax3.imshow(ss, cmap=cm.coolwarm, extent=ext, aspect='auto')
        fig.colorbar(im3, ax=ax3)

        self._im = [im1, im2, im3]

        self._counter = 0

        plt.draw()
        plt.pause(.1) 
Example 22
Project: hypermax   Author: electricbrainio   File: simulation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createInteractionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    param2 = algo.createHyperParameter()
    interaction = algo.createHyperParameterInteraction(param1, param2, type=3)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

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

    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfrom scipy.stats import norm\nfunc = " + interaction['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)
    yVals = numpy.linspace(0, 1, 25)

    grid = []
    for x in xVals:
        row = []
        for y in yVals:
            row.append(func(x, y)[0])
        grid.append(row)

    # Plot the surface.
    xVals, yVals = numpy.meshgrid(xVals, yVals)
    surf = ax.plot_surface(xVals, yVals, numpy.array(grid), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    # Customize the z axis.
    ax.set_zlim(0, 1.00)
    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() 
Example 23
Project: hypermax   Author: electricbrainio   File: simulation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createContributionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    contribution = algo.createHyperParameterContribution(param1, type=4)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig, ax = plt.subplots()

    print(contribution['func'])
    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfunc = " + contribution['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)

    yVals = []
    for x in xVals:
        yVals.append(func(x))

    # Plot the surface.
    surf = ax.scatter(numpy.array(xVals), numpy.array(yVals), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    plt.show() 
Example 24
Project: hypermax   Author: electricbrainio   File: simulation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createInteractionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    param2 = algo.createHyperParameter()
    interaction = algo.createHyperParameterInteraction(param1, param2, type=3)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

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

    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfrom scipy.stats import norm\nfunc = " + interaction['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)
    yVals = numpy.linspace(0, 1, 25)

    grid = []
    for x in xVals:
        row = []
        for y in yVals:
            row.append(func(x, y)[0])
        grid.append(row)

    # Plot the surface.
    xVals, yVals = numpy.meshgrid(xVals, yVals)
    surf = ax.plot_surface(xVals, yVals, numpy.array(grid), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    # Customize the z axis.
    ax.set_zlim(0, 1.00)
    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() 
Example 25
Project: hypermax   Author: electricbrainio   File: simulation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createContributionChartExample(type=4):
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    contribution = algo.createHyperParameterContribution(param1, type=type)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig, ax = plt.subplots()

    print(contribution['func'])
    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfunc = " + contribution['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)

    yVals = []
    for x in xVals:
        yVals.append(func(x))

    # Plot the surface.
    surf = ax.scatter(numpy.array(xVals), numpy.array(yVals), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    plt.show() 
Example 26
Project: L2L   Author: IGITUGraz   File: tools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot(fn, random_state):
    """
    Implements plotting of 2D functions generated by FunctionGenerator
    :param fn: Instance of FunctionGenerator
    """
    import numpy as np
    from l2l.matplotlib_ import plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    fig = plt.figure()
    ax = fig.gca(projection=Axes3D.name)

    # Make data.
    X = np.arange(fn.bound[0], fn.bound[1], 0.05)
    Y = np.arange(fn.bound[0], fn.bound[1], 0.05)
    XX, YY = np.meshgrid(X, Y)
    Z = [fn.cost_function([x, y], random_state=random_state) for x, y in zip(XX.ravel(), YY.ravel())]
    Z = np.array(Z).reshape(XX.shape)

    # Plot the surface.
    surf = ax.plot_surface(XX, YY, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

    # Customize the z axis.
    # ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    W = np.where(Z == np.min(Z))
    ax.set(title='Min value is %.2f at (%.2f, %.2f)' % (np.min(Z), X[W[0]], Y[W[1]]))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.savefig('function.png')
    plt.show() 
Example 27
Project: SqueezeMeta   Author: jtamames   File: density.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot(self, data, xlabel, ylabel):
        # set size of figure
        self.fig.clear()
        self.fig.set_size_inches(self.options.width, self.options.height)
        axis = self.fig.add_subplot(111)
        
        cax = axis.imshow(data, cmap=cm.coolwarm)
        cbar = self.fig.colorbar(cax)

        axis.set_xlabel(xlabel)
        axis.set_ylabel(ylabel)
        
        axis.set_yticks([0, 4, 8, 12, 16, 20])
        axis.set_yticklabels(['100', '90', '80', '70', '60', '50'])
        
        # *** Prettify plot
        for line in axis.yaxis.get_ticklines(): 
            line.set_color(self.axes_colour)
                
        for line in axis.xaxis.get_ticklines(): 
            line.set_color(self.axes_colour)
            
        for loc, spine in axis.spines.items():
            spine.set_color(self.axes_colour)

        self.fig.tight_layout(pad=1.0, w_pad=0.1, h_pad=0.1)
        self.draw() 
Example 28
Project: snn4hrl   Author: florensacc   File: plt_results2D.py    License: MIT License 5 votes vote down vote up
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 
Example 29
Project: Conditional_Density_Estimation   Author: freelunchtheorem   File: BaseConditionalDensitySimulation.py    License: MIT License 4 votes vote down vote up
def plot(self, xlim=(-5, 5), ylim=(-5, 5), resolution=100, mode="pdf", show=False, numpyfig=False):
    """ Plots the distribution specified in mode if x and y are 1-dimensional each

    Args:
      xlim: 2-tuple specifying the x axis limits
      ylim: 2-tuple specifying the y axis limits
      resolution: integer specifying the resolution of plot
      mode: spefify which dist to plot ["pdf", "cdf", "joint_pdf"]

    """
    modes = ["pdf", "cdf", "joint_pdf"]
    assert mode in modes, "mode must be on of the following: " + modes
    assert self.ndim == 2, "Can only plot two dimensional distributions"

    if show == False and mpl.is_interactive():
      plt.ioff()


    # prepare mesh
    linspace_x = np.linspace(xlim[0], xlim[1], num=resolution)
    linspace_y = np.linspace(ylim[0], ylim[1], num=resolution)
    X, Y = np.meshgrid(linspace_x, linspace_y)
    X, Y = X.flatten(), Y.flatten()

    # calculate values of distribution
    if mode == "pdf":
      Z = self.pdf(X, Y)
    elif mode == "cdf":
      Z = self.cdf(X, Y)
    elif mode == "joint_pdf":
      Z = self.joint_pdf(X, Y)

    X, Y, Z = X.reshape([resolution, resolution]), Y.reshape([resolution, resolution]), Z.reshape(
      [resolution, resolution])
    fig = plt.figure(dpi=300)
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, rcount=resolution, ccount=resolution,
                           linewidth=100, antialiased=True)
    plt.xlabel("x")
    plt.ylabel("y")
    if show:
      plt.show()

    if numpyfig:
      fig.tight_layout(pad=0)
      fig.canvas.draw()
      numpy_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
      numpy_img = numpy_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
      return numpy_img

    return fig 
Example 30
Project: Conditional_Density_Estimation   Author: freelunchtheorem   File: BaseConditionalDensity.py    License: MIT License 4 votes vote down vote up
def plot3d(self, xlim=(-5, 5), ylim=(-8, 8), resolution=100, show=False, numpyfig=False):
    """ Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each

    Args:
      xlim: 2-tuple specifying the x axis limits
      ylim: 2-tuple specifying the y axis limits
      resolution: integer specifying the resolution of plot
    """
    assert self.ndim_x + self.ndim_y == 2, "Can only plot two dimensional distributions"

    if show == False and mpl.is_interactive():
      plt.ioff()
      mpl.use('Agg')

    # prepare mesh
    linspace_x = np.linspace(xlim[0], xlim[1], num=resolution)
    linspace_y = np.linspace(ylim[0], ylim[1], num=resolution)
    X, Y = np.meshgrid(linspace_x, linspace_y)
    X, Y = X.flatten(), Y.flatten()

    # calculate values of distribution
    Z = self.pdf(X, Y)

    X, Y, Z = X.reshape([resolution, resolution]), Y.reshape([resolution, resolution]), Z.reshape(
      [resolution, resolution])
    fig = plt.figure(dpi=300)
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, rcount=resolution, ccount=resolution,
                           linewidth=100, antialiased=True)
    plt.xlabel("x")
    plt.ylabel("y")
    if show:
      plt.show()

    if numpyfig:
      fig.tight_layout(pad=0)
      fig.canvas.draw()
      numpy_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
      numpy_img = numpy_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
      return numpy_img

    return fig