Python matplotlib.pyplot.contourf() Examples

The following are code examples for showing how to use matplotlib.pyplot.contourf(). 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: shenfun   Author: spectralDNS   File: RayleighBenardRK3.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot(self, t, tstep):
        if tstep % self.modplot == 0:
            ub = self.u_.backward(self.ub)
            e0 = dx(ub[0]*ub[0])
            e1 = dx(ub[1]*ub[1])
            T_b = self.T_.backward(self.T_b)
            e2 = inner(1, T_b*T_b)
            div_u = project(div(self.u_), self.TD).backward()
            e3 = dx(div_u*div_u)
            if comm.Get_rank() == 0:
                print("Time %2.5f Energy %2.6e %2.6e %2.6e div %2.6e" %(t, e0, e1, e2, e3))

                plt.figure(1)
                self.im1.set_UVC(ub[1], ub[0])
                self.im1.scale = np.linalg.norm(ub[1])
                plt.pause(1e-6)
                plt.figure(2)
                self.im2.ax.clear()
                self.im2.ax.contourf(self.X[1], self.X[0], T_b, 100)
                self.im2.autoscale()
                plt.pause(1e-6) 
Example 2
Project: ESL   Author: jayshonzs   File: LDA.py    MIT License 6 votes vote down vote up
def draw(data, classes, means, thegma, pi, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(inputs[i], means, thegma, pi, 3))
    result = np.array(z).reshape(xx1.shape)
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    plt.show() 
Example 3
Project: ESL   Author: jayshonzs   File: QDA.py    MIT License 6 votes vote down vote up
def draw(data, classes, means, thegmas, pi, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(inputs[i], means, thegmas, pi, 3))
    result = np.array(z).reshape(xx1.shape)
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    plt.show() 
Example 4
Project: ESL   Author: jayshonzs   File: Fisher.py    MIT License 6 votes vote down vote up
def draw(data, outputs, centroids, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(centroids, inputs[i]))
    result = np.array(z).reshape(xx1.shape)
    np.savetxt('result.out', result, delimiter=',', fmt='%2d')
    plt.contourf(xx1, xx2, result, 12, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=outputs, cmap=mycm)
    plt.scatter(centroids[:, 0], centroids[:, 1], c=np.array([1,2,3,4,5,6,7,8,9,10,11]), marker='^', s=200, cmap=mycm)
    
    plt.show() 
Example 5
Project: ESL   Author: jayshonzs   File: SimulateClassifySVM.py    MIT License 6 votes vote down vote up
def draw(data, classes, sv, alphas, b, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(SMO.predict(data, classes, alphas, b, inputs[i]))
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    plt.scatter(sv[:,0], sv[:,1], s=10)
    
    plt.show() 
Example 6
Project: ESL   Author: jayshonzs   File: knn.py    MIT License 6 votes vote down vote up
def drawclass(X, Y, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = X[:, 0].min()-0.1, X[:, 0].max()+0.1
    two_min, two_max = X[:, 1].min()-0.1, X[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        res = knn(X, Y, 15, inputs[i])
        z.append(res)
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(X[:,0], X[:,1], s=30, c=Y, cmap=mycm)
    
    plt.show() 
Example 7
Project: ESL   Author: jayshonzs   File: bayes_classify.py    MIT License 6 votes vote down vote up
def drawclass(X, Y, C, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = X[:, 0].min()-0.1, X[:, 0].max()+0.1
    two_min, two_max = X[:, 1].min()-0.1, X[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        res = bayes_classify(inputs[i], C)
        z.append(res)
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(X[:,0], X[:,1], s=30, c=Y, cmap=mycm)
    
    plt.show() 
Example 8
Project: ESL   Author: jayshonzs   File: K_means.py    MIT License 6 votes vote down vote up
def draw(data, classes, model, resolution=100):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(predict(model, inputs[i]))
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    centers, t = extract_centers(model)
    plt.scatter(centers[:, 0], centers[:, 1], s=150, c=t, cmap=mycm)
    
    plt.xlim([0, 10])
    plt.ylim([0, 10])
    
    plt.show() 
Example 9
Project: ESL   Author: jayshonzs   File: NeuralNetwork.py    MIT License 6 votes vote down vote up
def drawclass(X, Y, alpha, beta, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = X[:, 0].min()-0.1, X[:, 0].max()+0.1
    two_min, two_max = X[:, 1].min()-0.1, X[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        res = predict(inputs[i], alpha, beta)
        z.append(res)
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(X[:,0], X[:,1], s=30, c=Y, cmap=mycm)
    
    plt.show() 
Example 10
Project: easydl   Author: thuml   File: visualization.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(predictor, xs, ys):
    '''
    plot 2D decision boundary for a classifier.
    ``predictor`` shoule be a function, which can be called with ``predictor(data)``, where data has (n_sample, 2) shape
    ``xs`` should be a sequence representing the grid's x coordinates
    ``ys`` should be a sequence representing the grid's y coordinates

    example usage::

    plot_decision_boundary(func, np.arange(-6.0, 8.0, 0.1), np.arange(-8.0, 8.0, 0.1))

    '''
    xx, yy = np.meshgrid(xs, ys, indexing='ij')
    data = np.asarray([xx.flatten(), yy.flatten()]).T
    label = predictor(data)
    label.resize(xx.shape)
    plt.contourf(xx, yy, label, alpha=0.3) 
Example 11
Project: Autoenv   Author: intelligent-control-lab   File: terrain.py    MIT License 6 votes vote down vote up
def save_texture(x, y, hfield, fname, path=None):
    '''
    @param path, str (optional). If not provided, DEFAULT_PATH is used. Make sure this matches the <texturedir> of the
        <compiler> element in the env XML
    '''
    path = _checkpath(path)
    plt.figure()
    plt.contourf(x, y, -hfield, 100, cmap=TERRAIN_CMAP)
    xmin, xmax = x.min(), x.max()
    ymin, ymax = y.min(), y.max()
    # for some reason plt.grid does not work here, so generate gridlines manually
    for i in np.arange(xmin,xmax,0.5):
        plt.plot([i,i], [ymin,ymax], 'k', linewidth=0.1)
    for i in np.arange(ymin,ymax,0.5):
        plt.plot([xmin,xmax],[i,i], 'k', linewidth=0.1)
    plt.savefig(os.path.join(path, fname), bbox_inches='tight')
    plt.close() 
Example 12
Project: reconstruction   Author: microelly2   File: elevationgrid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def showHeightMap(x,y,z,zi):
	''' show height map in maptplotlib '''
	zi=zi.transpose()

	plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	plt.colorbar()

	CS = plt.contour(zi,15,linewidths=0.5,colors='k',
			   extent=[ y.min(), y.max(),x.min(), x.max()])
	CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, 
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	z=z.transpose()
	plt.scatter(y, x, c=z)

	# achsen umkehren
	#plt.gca().invert_xaxis()
	#plt.gca().invert_yaxis()

	plt.show()
	return 
Example 13
Project: paper-monogenic-signal   Author: pinga-lab   File: synthetic.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_monogenic(attributes, titles):
    # Plotting the attributes of the Monogenic Signal
    plt.figure(figsize=(20, 5))
    for i, par in enumerate(attributes):
        plt.subplot(1, 3, i + 1)
        plt.title(title[i])
        plt.gca().set_aspect('equal', adjustable='box')
        plt.contourf(yp/1000., xp/1000., par, 50, cmap=plt.cm.RdBu_r)
        cb = plt.colorbar(pad=0.05)
        if i:
            cb.set_label("Radians", labelpad=5, rotation=90)
        else:
            cb.set_label("nT", labelpad=5, rotation=90)
        plt.xlabel('Easting Coordinate (km)')
        plt.ylabel('Northing Coordinate (km)')
        plot_edges(2)
        plt.show()

# Open File "data.dat" and import data 
Example 14
Project: geodata   Author: microelly2   File: elevationgrid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def showHeightMap(x,y,z,zi):
	''' show height map in maptplotlib '''
	zi=zi.transpose()

	plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	plt.colorbar()

	CS = plt.contour(zi,15,linewidths=0.5,colors='k',
			   extent=[ y.min(), y.max(),x.min(), x.max()])
	CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, 
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	z=z.transpose()
	plt.scatter(y, x, c=z)

	# achsen umkehren
	#plt.gca().invert_xaxis()
	#plt.gca().invert_yaxis()

	plt.show()
	return 
Example 15
Project: Qualia2.0   Author: Kashu7100   File: basic.py    MIT License 6 votes vote down vote up
def show_decision_boundary(self, model):
        h = 0.001
        x, y = np.meshgrid(np.arange(-1, 1, h), np.arange(-1, 1, h))
        out = model(Tensor(np.c_[x.ravel(), y.ravel()]))
        pred = np.argmax(out.data, axis=1)
        if gpu:
            plt.contourf(to_cpu(x), to_cpu(y), to_cpu(pred.reshape(x.shape)))
            for c in range(self.num_class):
                plt.scatter(to_cpu(self.data[(self.label[:,c]>0)][:,0]),to_cpu(self.data[(self.label[:,c]>0)][:,1]))
        else:
            plt.contourf(x, y, pred.reshape(x.shape))
            for c in range(self.num_class):
                plt.scatter(self.data[(self.label[:,c]>0)][:,0],self.data[(self.label[:,c]>0)][:,1])
        plt.xlim(-1,1)
        plt.ylim(-1,1)
        plt.axis('off')
        plt.show() 
Example 16
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 6 votes vote down vote up
def dummy_plot(aspect_ratio_equal=False, contour=False):
	if contour:
		delta = 0.025
		x = np.arange(-3.0, 3.0, delta)
		y = np.arange(-3.0, 3.0, delta)
		X, Y = np.meshgrid(x, y)
		Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
		Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
		# difference of Gaussians
		Z = 10.0 * (Z2 - Z1)
		plt.contourf(X, Y, Z)
	else:
		plt.plot([1,2,3,4])
	if aspect_ratio_equal:
		ax = plt.gca()
		ax.set_aspect('equal')
		ax.set_xticks([])
		ax.set_yticks([])
	return plt.gca() 
Example 17
Project: pyxe   Author: casimp   File: peak_analysis.py    MIT License 6 votes vote down vote up
def plot_temperature(self, order=None):
        """ Plot temperature distribution across sample/data.
        
        Args:
            order (int): Ndims of data
        """
        
        order = self.ndim if order is None else order
        if order == 1:
            plt.plot(self.d1, self.T) 
        else:
            if self.ndim > len(self.d1.shape):
                d1i = np.linspace(self.d1.min(), self.d1.max(), 100)
                d2i = np.linspace(self.d2.min(), self.d2.max(), 100)
                d1, d2 = np.meshgrid(d1i, d2i)
                T = griddata((self.d1, self.d2), self.T, (d1, d2))
                plt.contourf(d1, d2, T)
                plt.colorbar()
            else:
                plt.contourf(self.d1, self.d2, self.T)
                plt.colorbar() 
Example 18
Project: ocelot   Author: ocelot-collab   File: accelerator.py    GNU General Public License v3.0 6 votes vote down vote up
def show_da(out_da, x_array, y_array, title=""):
    #print "time execution = ", time() - start , " s"
    nx = len(x_array)
    ny = len(y_array)
    #print(nx, ny, len(out_da))
    out_da = out_da.reshape(ny,nx)
    xmin, xmax, ymin, ymax = np.min(x_array), np.max(x_array), np.min(y_array), np.max(y_array)
    #plt.subplot(111, axisbg='darkslategray')
    extent = xmin, xmax, ymin, ymax
    #print extent
    #plt.savetxt("da.txt", da)
    plt.figure(figsize=(10, 7))
    fig1 = plt.contour(out_da, linewidths=2,extent = extent)#, colors = 'r')
    #fig1 = plt.contourf(out_da, 20,cmap=plt.cm.rainbow,extent = extent)#, colors = 'r')
    #plt.axis_bgcolor("#bdb76b")
    plt.grid(True)
    plt.title(title)
    plt.xlabel("X, m")
    plt.ylabel("Y, m")
    cb = plt.colorbar()
    cb.set_label('Nturns')
    #cb.ax.set_yticklabels(map(str, linspace(min(out_da), max(out_da), 5) ))

    #plt.savefig('da_error_'+str(int(np.random.rand()*100))+'.png')
    plt.show() 
Example 19
Project: nntour   Author: miku   File: minimal.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(pred_func, X, y):
    """
    Set min and max values and give it some padding.
    """
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    h = 0.01

    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) 
Example 20
Project: nntour   Author: miku   File: xornn.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(pred_func, X, y):
    """
    Set min and max values and give it some padding.
    """
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    h = 0.01

    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) 
Example 21
Project: ble5-nrf52-mac   Author: tomasero   File: test_colorbar.py    MIT License 6 votes vote down vote up
def test_colorbar_get_ticks():
    # test feature for #5792
    plt.figure()
    data = np.arange(1200).reshape(30, 40)
    levels = [0, 200, 400, 600, 800, 1000, 1200]

    plt.subplot()
    plt.contourf(data, levels=levels)

    # testing getter for user set ticks
    userTicks = plt.colorbar(ticks=[0, 600, 1200])
    assert userTicks.get_ticks().tolist() == [0, 600, 1200]

    # testing for getter after calling set_ticks
    userTicks.set_ticks([600, 700, 800])
    assert userTicks.get_ticks().tolist() == [600, 700, 800]

    # testing for getter after calling set_ticks with some ticks out of bounds
    userTicks.set_ticks([600, 1300, 1400, 1500])
    assert userTicks.get_ticks().tolist() == [600]

    # testing getter when no ticks are assigned
    defTicks = plt.colorbar(orientation='horizontal')
    assert defTicks.get_ticks().tolist() == levels 
Example 22
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 6 votes vote down vote up
def test_given_colors_levels_and_extends():
    _, axes = plt.subplots(2, 4)

    data = np.arange(12).reshape(3, 4)

    colors = ['red', 'yellow', 'pink', 'blue', 'black']
    levels = [2, 4, 8, 10]

    for i, ax in enumerate(axes.flatten()):
        filled = i % 2 == 0.
        extend = ['neither', 'min', 'max', 'both'][i // 2]

        if filled:
            # If filled, we have 3 colors with no extension,
            # 4 colors with one extension, and 5 colors with both extensions
            first_color = 1 if extend in ['max', 'neither'] else None
            last_color = -1 if extend in ['min', 'neither'] else None
            c = ax.contourf(data, colors=colors[first_color:last_color],
                            levels=levels, extend=extend)
        else:
            # If not filled, we have 4 levels and 4 colors
            c = ax.contour(data, colors=colors[:-1],
                           levels=levels, extend=extend)

        plt.colorbar(c, ax=ax) 
Example 23
Project: missshi_deeplearning_ai   Author: wangzhe0912   File: init_utils.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    plt.show() 
Example 24
Project: missshi_deeplearning_ai   Author: wangzhe0912   File: opt_utils.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    plt.show() 
Example 25
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: simple_functions.py    MIT License 6 votes vote down vote up
def plot_f(f, filenm='test_function.eps'):
    # only for 2D functions
    import matplotlib.pyplot as plt
    import matplotlib
    font = {'size': 20}
    matplotlib.rc('font', **font)

    delta = 0.005
    x = np.arange(0.0, 1.0, delta)
    y = np.arange(0.0, 1.0, delta)
    nx = len(x)
    X, Y = np.meshgrid(x, y)

    xx = np.array((X.ravel(), Y.ravel())).T
    yy = f(xx)

    plt.figure()
    plt.contourf(X, Y, yy.reshape(nx, nx), levels=np.linspace(yy.min(), yy.max(), 40))
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.colorbar()
    plt.scatter(f.argmax[0], f.argmax[1], s=180, color='k', marker='+')
    plt.savefig(filenm) 
Example 26
Project: skultrafast   Author: Tillsten   File: plot_helpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nice_map(wl,
             t,
             d,
             lvls=20,
             linthresh=10,
             linscale=1,
             norm=None,
             linscaley=1,
             cmap='coolwarm',
             **kwargs):
    if norm is None:
        norm = SymLogNorm(linthresh, linscale=linscale)
    con = plt.contourf(wl, t, d, lvls, norm=norm, cmap=cmap, **kwargs)
    cb = plt.colorbar(pad=0.02)
    cb.set_label(sig_label)
    plt.contour(wl, t, d, lvls, norm=norm, colors='black', lw=.5, linestyles='solid')

    plt.yscale('symlog', linthreshy=1, linscaley=linscaley, suby=[2, 3, 4, 5, 6, 7, 8, 9])
    plt.ylim(-.5, )
    plt.xlabel(freq_label)
    plt.ylabel(time_label)
    return con 
Example 27
Project: MachineLearning_Python   Author: lawlite19   File: AnomalyDetection.py    MIT License 6 votes vote down vote up
def visualizeFit(X,mu,sigma2):
    x = np.arange(0, 36, 0.5) # 0-36,步长0.5
    y = np.arange(0, 36, 0.5)
    X1,X2 = np.meshgrid(x,y)  # 要画等高线,所以meshgird
    Z = multivariateGaussian(np.hstack((X1.reshape(-1,1),X2.reshape(-1,1))), mu, sigma2)  # 计算对应的高斯分布函数
    Z = Z.reshape(X1.shape)  # 调整形状
    plt.plot(X[:,0],X[:,1],'bx')
    
    if np.sum(np.isinf(Z).astype(float)) == 0:   # 如果计算的为无穷,就不用画了
        #plt.contourf(X1,X2,Z,10.**np.arange(-20, 0, 3),linewidth=.5)
        CS = plt.contour(X1,X2,Z,10.**np.arange(-20, 0, 3),color='black',linewidth=.5)   # 画等高线,Z的值在10.**np.arange(-20, 0, 3)
        #plt.clabel(CS)
            
    plt.show()

# 选择最优的epsilon,即:使F1Score最大 
Example 28
Project: pyiron   Author: pyiron   File: thermo_bulk.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contour_pressure(self):
        """

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        x, y = self.meshgrid()
        p_coeff = np.polyfit(self.volumes, self.pressure.T, deg=self._fit_order)
        p_grid = np.array([np.polyval(p_coeff, v) for v in self._volumes]).T
        plt.contourf(x, y, p_grid)
        plt.plot(self.get_minimum_energy_path(), self.temperatures)
        plt.xlabel("Volume [$\AA^3$]")
        plt.ylabel("Temperature [K]") 
Example 29
Project: pyiron   Author: pyiron   File: thermo_bulk.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contour_entropy(self):
        """

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        s_coeff = np.polyfit(self.volumes, self.entropy.T, deg=self._fit_order)
        s_grid = np.array([np.polyval(s_coeff, v) for v in self.volumes]).T
        x, y = self.meshgrid()
        plt.contourf(x, y, s_grid)
        plt.plot(self.get_minimum_energy_path(), self.temperatures)
        plt.xlabel("Volume [$\AA^3$]")
        plt.ylabel("Temperature [K]") 
Example 30
Project: pyiron   Author: pyiron   File: thermo_bulk.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_contourf(self, ax=None, show_min_erg_path=False):
        """

        Args:
            ax:
            show_min_erg_path:

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        x, y = self.meshgrid()
        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.contourf(x, y, self.energies)
        if show_min_erg_path:
            plt.plot(self.get_minimum_energy_path(), self.temperatures, "w--")
        plt.xlabel("Volume [$\AA^3$]")
        plt.ylabel("Temperature [K]")
        return ax 
Example 31
Project: neural-network-animation   Author: miloharper   File: test_contour.py    MIT License 6 votes vote down vote up
def test_contour_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(20)])
    y = np.arange(20)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.contour(x, y, z)
    plt.subplot(222)
    plt.contourf(x, y, z)
    x = np.repeat(x[np.newaxis], 20, axis=0)
    y = np.repeat(y[:, np.newaxis], 20, axis=1)
    plt.subplot(223)
    plt.contour(x, y, z)
    plt.subplot(224)
    plt.contourf(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 32
Project: shenfun   Author: spectralDNS   File: Ginzburg_Landau.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, u, u_hat, t, tstep, plot_tstep, write_tstep, file, **params):
    global count
    if tstep % plot_tstep == 0 and plot_tstep > 0:
        u = u_hat.backward(u)
        image.ax.clear()
        image.ax.contourf(X[0], X[1], u.real, 100)
        plt.pause(1e-6)
        count += 1
        #plt.savefig('Ginzburg_Landau_{}_{}.png'.format(N[0], count))
    if tstep % write_tstep[0] == 0:
        u = u_hat.backward(u)
        file.write(tstep, write_tstep[1]) 
Example 33
Project: shenfun   Author: spectralDNS   File: Gray_Scott_fractal.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, uv, uv_hat, t, tstep, **params):
    if tstep % params['plot_step'] == 0 and params['plot_step'] > 0:
        uv = uv_hat.backward(uv)
        image.ax.clear()
        image.ax.contourf(X[0], X[1], uv[0].real, 100)
        plt.pause(1e-6)
        print(np.linalg.norm(uv[0]-uv0[0]),
              np.linalg.norm(uv[1]-uv0[1]),
              np.linalg.norm(uv[0]),
              np.linalg.norm(uv[1]))
        uv0[:] = uv

    if tstep % params['write_tstep'][0] == 0:
        uv = uv_hat.backward(uv)
        params['file'].write(tstep, params['write_tstep'][1], as_scalar=True) 
Example 34
Project: shenfun   Author: spectralDNS   File: KleinGordon.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, fu, fu_hat, t, tstep, **params):
    global gradu

    timer()
    transformed = False

    if rank == 0 and tstep % params['plot_tstep'] == 0 and params['plot_tstep'] > 0:
        fu = fu_hat.backward(fu)
        f, u = fu[:]
        image.ax.clear()
        image.ax.contourf(X[1][..., 0], X[0][..., 0], u[..., N[2]//2], 100)
        plt.pause(1e-6)
        transformed = True

    if tstep % params['write_slice_tstep'][0] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
            transformed = True
        params['file'].write(tstep, params['write_slice_tstep'][1], as_scalar=True)

    if tstep % params['write_tstep'][0] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
            transformed = True
        params['file'].write(tstep, params['write_tstep'][1], as_scalar=True)

    if tstep % params['Compute_energy'] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
        f, u = fu
        f_hat, u_hat = fu_hat
        ekin = 0.5*energy_fourier(f_hat, T)
        es = 0.5*energy_fourier(1j*(K[0]*u_hat[0]+K[1]*u_hat[1]+K[2]*u_hat[2]), T)
        eg = gamma*np.sum(0.5*u**2 - 0.25*u**4)/np.prod(np.array(N))
        eg = comm.allreduce(eg)
        gradu = TV.backward(1j*(K[0]*u_hat[0]+K[1]*u_hat[1]+K[2]*u_hat[2]), gradu)
        ep = comm.allreduce(np.sum(f*gradu)/np.prod(np.array(N)))
        ea = comm.allreduce(np.sum(np.array(X)*(0.5*f**2 + 0.5*gradu**2 - (0.5*u**2 - 0.25*u**4)*f))/np.prod(np.array(N)))
        if rank == 0:
            print("Time = %2.2f Total energy = %2.8e Linear momentum %2.8e Angular momentum %2.8e" %(t, ekin+es+eg, ep, ea))
        comm.barrier() 
Example 35
Project: shenfun   Author: spectralDNS   File: RayleighBenardRK3.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_plots(self):
        ub = self.u_.backward(self.ub)
        T_b = self.T_.backward(self.T_b)
        if comm.Get_rank() == 0:
            plt.figure(1, figsize=(6, 3))
            self.im1 = plt.quiver(self.X[1], self.X[0], ub[1], ub[0], pivot='mid', scale=0.01)
            plt.draw()
            plt.figure(2, figsize=(6, 3))
            self.im2 = plt.contourf(self.X[1], self.X[0], T_b, 100)
            plt.draw()
            plt.pause(1e-6) 
Example 36
Project: ESL   Author: jayshonzs   File: LVQ.py    MIT License 5 votes vote down vote up
def draw(data, classes, model, resolution=100):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(predict(model, inputs[i])[0])
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    t = np.zeros(15)
    for i in range(15):
        if i < 5:
            t[i] = 0
        elif i < 10:
            t[i] = 1
        else:
            t[i] = 2
    plt.scatter(model[:, 0], model[:, 1], s=150, c=t, cmap=mycm)
    
    plt.xlim([0, 10])
    plt.ylim([0, 10])
    
    plt.show() 
Example 37
Project: Autoenv   Author: intelligent-control-lab   File: terrain.py    MIT License 5 votes vote down vote up
def save_heightfield(x, y, hfield, fname, path=None):
    '''
    @param path, str (optional). If not provided, DEFAULT_PATH is used. Make sure the path + fname match the <file> attribute
        of the <asset> element in the env XML where the height field is defined
    '''
    path = _checkpath(path)
    plt.figure()
    plt.contourf(x, y, -hfield, 100, cmap=TERRAIN_CMAP) # terrain_cmap is necessary to make sure tops get light color
    plt.savefig(os.path.join(path, fname), bbox_inches='tight')
    plt.close() 
Example 38
Project: TF_RL   Author: Rowing0914   File: utils.py    MIT License 5 votes vote down vote up
def visualise_critic_values(env, agent, flg="DDPG"):
    """ Visualise the Critic using a meshgrid to traverse the whole 2D world """
    high, low = env.observation_space.high, env.observation_space.low
    x = np.linspace(start=low[0], stop=high[0], num=1000)
    y = np.linspace(start=low[1], stop=high[1], num=1000)

    print("=== Evaluation Mode ===")
    data = np.stack([x, y], axis=-1).astype(np.float32)

    if flg == "DDPG":
        res = agent.critic(data, agent.eval_predict(data)).numpy().flatten()
    elif flg == "SAC":
        res = agent.critic(data, agent.eval_predict(data))[0].numpy().flatten()
    else:
        assert False, "Choose either DDPG or SAC"

    print(res.shape, x.shape, x.shape)
    print("Max Q: {}, Min Q: {}".format(res.max(), res.min()))

    import matplotlib.pyplot as plt
    from scipy.interpolate import griddata

    X, Y = np.meshgrid(x, y)
    Z = griddata((x, y), res, (X, Y), method='nearest')
    env._visualise_setup()
    plt.contourf(X, Y, Z)
    plt.colorbar()
    plt.show() 
Example 39
Project: pyretina   Author: yandexdataschool   File: plot.py    Apache License 2.0 5 votes vote down vote up
def plot_retina_results(predicted, event, max_angle, search_traces = None, against = 'true'):
  thetas, phis, response = event.get_grid()

  m, test, predicted_mapping, test_mapping = binary_metrics(predicted, event, max_angle=max_angle, against = against)
  recognized = predicted_mapping == 1
  test_recognized = test_mapping == 1
  ghost = predicted_mapping == 0
  unrecognized = test_mapping == 0

  plt.figure(figsize=(48, 48))
  plt.contourf(thetas, phis, response, 40, cmap=cm.gist_gray)
  plt.colorbar()

  plt.scatter(predicted[recognized, 0], predicted[recognized, 1], color="green", marker="+",
              label="Recognized (%d)" % np.sum(test_recognized), s=80)

  plt.scatter(test[test_recognized, 0], test[test_recognized, 1], color="green", marker="o",
              s=40)


  plt.scatter(predicted[ghost, 0], predicted[ghost, 1], color="red", marker="x",
              label="Ghost (%d)" % np.sum(ghost), s=80)

  plt.scatter(test[unrecognized, 0], test[unrecognized, 1], color="red", marker="o",
              label="Unrecognized (%d)" % np.sum(unrecognized), s=80)

  if search_traces is not None:
    for trace in search_traces:
      xs = [ p[0] for p in trace ]
      ys = [ p[1] for p in trace ]

      plt.plot(xs, ys, color="blue")

  plt.legend()
  return plt 
Example 40
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def input_norm(self, populations=['exc', 'inh'], ylim=None):
        for psp in self.psps:
            self.set_params_rawdata_computed(psp, set_sim_params=True)
            rawdata = self.rawdata
            for p in populations:
                if self.dimensions == 1:
                    plt.plot(rawdata[p]['input_norm'], color=self.colors[p])
                    plt.ylim(ylim)

                elif self.dimensions == 2:
                    centers_x = rawdata[p]['centers'][:,0,0]
                    centers_y = rawdata[p]['centers'][:,0,1]
                    colors =  rawdata[p]['input_norm']
                    # color_norm = mpl.colors.Normalize(np.amin(colors), np.amax(colors))
                    # plt.scatter(centers_x, centers_y, c=colors, alpha=0.5, cmap=mpl.cm.jet, norm=color_norm)
                    plt.scatter(centers_x, centers_y, c='blue', alpha=0.1)
                    # plt.colorbar()


                    lim = [-self.radius-0.05, self.radius+0.05]
                    plt.xlim(lim)
                    plt.ylim(lim)
                    ax = plt.gca()
                    ax.set_aspect('equal')
                    plt.hlines([-self.radius, self.radius], -self.radius, self.radius)
                    plt.vlines([-self.radius, self.radius], -self.radius, self.radius)

                    # plt.contourf(rawdata['exc']['centers'][:,0,0].reshape((10, 10))) 
Example 41
Project: spatial_patterns   Author: sim-web   File: test_observables.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_illustration_of_array_with_angles(self):
        # Note: the vertical axis is the x axis
        # You need to turn everthing counterclockwise by 90 degrees in order
        # to get the values for angles
        la = self.gridness_ones.labeled_array
        ### Contour plot ###
        plt.subplot(211)
        plt.contourf(la)
        plt.gca().set_aspect('equal')
        ### Imshow plot ###
        plt.subplot(212)
        plt.imshow(la, interpolation='none', origin='lower')
        ax = plt.gca()
        x_n = la.shape[1]
        y_n = la.shape[0]
        ax.set_xticks(np.linspace(0, x_n-1, x_n))
        ax.set_yticks(np.linspace(0, y_n-1, y_n))
        ax.set_xlim(-.5, x_n-.5)
        ax.set_ylim(-.5, y_n-.5)
        x_names = [str(x) for x in range(x_n)]
        y_names = [str(x) for x in range(y_n)]
        ax.set_xticklabels(x_names, rotation=45., minor=False)
        ax.set_yticklabels(y_names, rotation=45., minor=False)
        for angle in self.gridness_ones.get_grid_axes_angles():
            plt.plot(np.array([0, 3*np.cos(angle)])+3,
                     np.array([0, 3*np.sin(angle)])+3, marker='o', color='red')
        plt.show() 
Example 42
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def two_dimensional_input_tuning():
	x, y = np.mgrid[-1:1:.01, -1:1:.01]
	pos = np.dstack((x, y))
	gaussian = scipy.stats.multivariate_normal([0., 0.], np.power([0.05, 0.1], 2))
	vanishing_value = 1e-1
	# fields = field(positions, location, sigma_exc).reshape((n_x, n_x))
	cm = mpl.cm.Reds
	my_masked_array = np.ma.masked_less(gaussian.pdf(pos), vanishing_value)
	plt.contourf(x, y, my_masked_array, cmap=cm)
	ax = plt.gca()
	# ax.set_aspect('equal')
	plt.setp(ax, aspect='equal', xticks=[], yticks=[])
	plt.axis('off')


# def plot_grid_score_histogram(grid_scores, start_frame=0, end_frame=-1):
# 	"""
# 	Grid score histogram
#
# 	Parameters
# 	----------
#
#
# 	Returns
# 	-------
# 	"""
# 	# date_dir = '2016-04-01-10h24m43s_600_minutes_very_fast_learning'
# 	# tables = get_tables(date_dir=date_dir)
# 	# plot = plotting.Plot(tables=tables, psps=None)
# 	# grid_score = plot.tables.get_computed(None)['grid_score']
# 	# print grid_score['Weber']['1'].shape
# 	hist_kwargs = {'alpha': 0.5, 'bins': 20}
# 	grid_scores = grid_score['Weber']['1'][:, end_frame]
# 	grid_scores = grid_scores[~np.isnan(grid_scores)]
# 	plt.hist(grid_scores, **hist_kwargs)
# 	print grid_scores 
Example 43
Project: pyxe   Author: casimp   File: data_creation.py    MIT License 5 votes vote down vote up
def plot_strain_map(self, phi=np.pi/2, shear=False):
        e = self.extract_strain_map(phi, shear)
        plt.contourf(self.x, self.y, e, 21)
        plt.show() 
Example 44
Project: pyxe   Author: casimp   File: data_creation.py    MIT License 5 votes vote down vote up
def plot_stress_map(self, phi=np.pi/2, shear=False):
        sig = self.extract_stress_map(phi, shear)
        plt.contourf(self.x, self.y, sig, 21)
        plt.show() 
Example 45
Project: ble5-nrf52-mac   Author: tomasero   File: test_colorbar.py    MIT License 5 votes vote down vote up
def test_gridspec_make_colorbar():
    plt.figure()
    data = np.arange(1200).reshape(30, 40)
    levels = [0, 200, 400, 600, 800, 1000, 1200]

    plt.subplot(121)
    plt.contourf(data, levels=levels)
    plt.colorbar(use_gridspec=True, orientation='vertical')

    plt.subplot(122)
    plt.contourf(data, levels=levels)
    plt.colorbar(use_gridspec=True, orientation='horizontal')

    plt.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0.25) 
Example 46
Project: ble5-nrf52-mac   Author: tomasero   File: test_colorbar.py    MIT License 5 votes vote down vote up
def test_colorbar_ticks():
    # test fix for #5673
    fig, ax = plt.subplots()
    x = np.arange(-3.0, 4.001)
    y = np.arange(-4.0, 3.001)
    X, Y = np.meshgrid(x, y)
    Z = X * Y
    clevs = np.array([-12, -5, 0, 5, 12], dtype=float)
    colors = ['r', 'g', 'b', 'c']
    cs = ax.contourf(X, Y, Z, clevs, colors=colors)
    cbar = fig.colorbar(cs, ax=ax, extend='neither',
                        orientation='horizontal', ticks=clevs)
    assert len(cbar.ax.xaxis.get_ticklocs()) == len(clevs) 
Example 47
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_corner_mask():
    n = 60
    mask_level = 0.95
    noise_amp = 1.0
    np.random.seed([1])
    x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))
    z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)
    mask = np.where(np.random.rand(n, n) >= mask_level, True, False)
    z = np.ma.array(z, mask=mask)

    for corner_mask in [False, True]:
        fig = plt.figure()
        plt.contourf(z, corner_mask=corner_mask) 
Example 48
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contourf_decreasing_levels():
    # github issue 5477.
    z = [[0.1, 0.3], [0.5, 0.7]]
    plt.figure()
    with pytest.raises(ValueError):
        plt.contourf(z, [1.0, 0.0]) 
Example 49
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contourf_symmetric_locator():
    # github issue 7271
    z = np.arange(12).reshape((3, 4))
    locator = plt.MaxNLocator(nbins=4, symmetric=True)
    cs = plt.contourf(z, locator=locator)
    assert_array_almost_equal(cs.levels, np.linspace(-12, 12, 5)) 
Example 50
Project: ble5-nrf52-mac   Author: tomasero   File: test_contour.py    MIT License 5 votes vote down vote up
def test_contourf_log_extension():
    # Test that contourf with lognorm is extended correctly
    fig = plt.figure(figsize=(10, 5))
    fig.subplots_adjust(left=0.05, right=0.95)
    ax1 = fig.add_subplot(131)
    ax2 = fig.add_subplot(132)
    ax3 = fig.add_subplot(133)

    # make data set with large range e.g. between 1e-8 and 1e10
    data_exp = np.linspace(-7.5, 9.5, 1200)
    data = np.power(10, data_exp).reshape(30, 40)
    # make manual levels e.g. between 1e-4 and 1e-6
    levels_exp = np.arange(-4., 7.)
    levels = np.power(10., levels_exp)

    # original data
    c1 = ax1.contourf(data,
                      norm=LogNorm(vmin=data.min(), vmax=data.max()))
    # just show data in levels
    c2 = ax2.contourf(data, levels=levels,
                      norm=LogNorm(vmin=levels.min(), vmax=levels.max()),
                      extend='neither')
    # extend data from levels
    c3 = ax3.contourf(data, levels=levels,
                      norm=LogNorm(vmin=levels.min(), vmax=levels.max()),
                      extend='both')
    plt.colorbar(c1, ax=ax1)
    plt.colorbar(c2, ax=ax2)
    plt.colorbar(c3, ax=ax3)