Python matplotlib.pyplot.contourf() Examples

The following are 30 code examples of matplotlib.pyplot.contourf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: AnomalyDetection.py    From MachineLearning_Python with MIT License 8 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 #2
Source File: misclassified_loc.py    From ConvNetQuake with MIT License 6 votes vote down vote up
def plot_proba_map(i, lat,lon, clusters, class_prob, label,
                   lat_event, lon_event):

    plt.clf()
    class_prob = class_prob / np.sum(class_prob)
    assert np.isclose(np.sum(class_prob),1)
    risk_map = np.zeros_like(clusters,dtype=np.float64)
    for cluster_id in range(len(class_prob)):
        x,y = np.where(clusters == cluster_id)
        risk_map[x,y] = class_prob[cluster_id]

    plt.contourf(lon,lat,risk_map,cmap='YlOrRd',alpha=0.9,
                 origin='lower',vmin=0.0,vmax=1.0)
    plt.colorbar()

    plt.plot(lon_event, lat_event, marker='+',c='k',lw='5')
    plt.contour(lon,lat,clusters,colors='k',hold='on')
    plt.xlim((min(lon),max(lon)))
    plt.ylim((min(lat),max(lat)))
    png_name = os.path.join(args.output,
                    '{}_pred_{}_label_{}.eps'.format(i,np.argmax(class_prob),
                                                     label))
    plt.savefig(png_name)
    plt.close() 
Example #3
Source File: test_contour.py    From neural-network-animation with 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()):
        plt.sca(ax)

        filled = i % 2 == 0.
        extend = ['neither', 'min', 'max', 'both'][i // 2]

        if filled:
            last_color = -1 if extend in ['min', 'max'] else None
            plt.contourf(data, colors=colors[:last_color], levels=levels,
                         extend=extend)
        else:
            last_level = -1 if extend == 'both' else None
            plt.contour(data, colors=colors, levels=levels[:last_level],
                        extend=extend)

        plt.colorbar() 
Example #4
Source File: thermo_bulk.py    From pyiron with 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 #5
Source File: thermo_bulk.py    From pyiron with 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 #6
Source File: thermo_bulk.py    From pyiron with 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 #7
Source File: test_colorbar.py    From twitter-stock-recommendation with 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 #8
Source File: test_contour.py    From twitter-stock-recommendation with 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 #9
Source File: simple_functions.py    From Ensemble-Bayesian-Optimization with 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 #10
Source File: test_contour.py    From neural-network-animation with 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 #11
Source File: Decision_Tree.py    From ml_code with Apache License 2.0 6 votes vote down vote up
def dt_classification():
    iris = datasets.load_iris()
    X = iris.data[:, 0:2]
    y = iris.target
    
    clf = tree.DecisionTreeClassifier()
    clf.fit(X, y)
    
    dot_data = tree.export_graphviz(clf, out_file=None,
                                    feature_names=iris.feature_names,  
                                    class_names=iris.target_names,  
                                    filled=True, rounded=True,  
                                    special_characters=True
                                    )
    graph = pydotplus.graph_from_dot_data(dot_data)
    graph.write_png("./tree_iris.png")
    
    # plot result
    xmin, xmax = X[:, 0].min() - 1, X[:, 0].max() + 1
    ymin, ymax = X[:, 1].min() - 1, X[:, 1].max() + 1
    plot_step = 0.02
    xx, yy = np.meshgrid(np.arange(xmin, xmax, plot_step),
                         np.arange(ymin, ymax, plot_step))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    
    # Plot the training points
    n_classes = 3
    plot_colors = "bry"
    for i, color in zip(range(n_classes), plot_colors):
        idx = np.where(y == i)
        plt.scatter(X[idx, 0], X[idx, 1], c=color, 
                    label=iris.target_names[i],
                    cmap=plt.cm.Paired) 
Example #12
Source File: plane_plot.py    From dnn-mode-connectivity with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plane(grid, values, vmax=None, log_alpha=-5, N=7, cmap='jet_r'):
    cmap = plt.get_cmap(cmap)
    if vmax is None:
        clipped = values.copy()
    else:
        clipped = np.minimum(values, vmax)
    log_gamma = (np.log(clipped.max() - clipped.min()) - log_alpha) / N
    levels = clipped.min() + np.exp(log_alpha + log_gamma * np.arange(N + 1))
    levels[0] = clipped.min()
    levels[-1] = clipped.max()
    levels = np.concatenate((levels, [1e10]))
    norm = LogNormalize(clipped.min() - 1e-8, clipped.max() + 1e-8, log_alpha=log_alpha)
    contour = plt.contour(grid[:, :, 0], grid[:, :, 1], values, cmap=cmap, norm=norm,
                          linewidths=2.5,
                          zorder=1,
                          levels=levels)
    contourf = plt.contourf(grid[:, :, 0], grid[:, :, 1], values, cmap=cmap, norm=norm,
                            levels=levels,
                            zorder=0,
                            alpha=0.55)
    colorbar = plt.colorbar(format='%.2g')
    labels = list(colorbar.ax.get_yticklabels())
    labels[-1].set_text(r'$>\,$' + labels[-2].get_text())
    colorbar.ax.set_yticklabels(labels)
    return contour, contourf, colorbar 
Example #13
Source File: report.py    From wub with Mozilla Public License 2.0 6 votes vote down vote up
def plot_heatmap(self, data_matrix, title="", xlab="", ylab="", colormap=plt.cm.jet):
        """Plot heatmap of data matrix.

        :param self: object.
        :param data_matrix: 2D array to be plotted.
        :param title: Figure title.
        :param xlab: X axis label.
        :param ylab: Y axis label.
        :param colormap: matplotlib color map.
        :retuns: None
        :rtype: object
        """
        """
        """
        fig = plt.figure()

        p = plt.contourf(data_matrix)
        plt.colorbar(p, orientation='vertical', cmap=colormap)

        self._set_properties_and_close(fig, title, xlab, ylab) 
Example #14
Source File: test_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" 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 #15
Source File: geometry.py    From dmsh with MIT License 6 votes vote down vote up
def plot(self, level_set=True):
        import matplotlib.pyplot as plt

        x0, x1, y0, y1 = self.bounding_box

        w = x1 - x0
        h = x1 - x0
        x = numpy.linspace(x0 - w * 0.1, x1 + w * 0.1, 101)
        y = numpy.linspace(y0 - h * 0.1, y1 + h * 0.1, 101)
        X, Y = numpy.meshgrid(x, y)

        Z = self.dist(numpy.array([X, Y]))

        if level_set:
            alpha = max([abs(numpy.min(Z)), abs(numpy.min(Z))])
            cf = plt.contourf(
                X, Y, Z, levels=20, cmap=plt.cm.coolwarm, vmin=-alpha, vmax=alpha
            )
            plt.colorbar(cf)

        # mark the 0-level (the domain boundary)
        plt.contour(X, Y, Z, levels=[0.0], colors="k")

        plt.gca().set_aspect("equal") 
Example #16
Source File: basic.py    From Qualia2.0 with 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 #17
Source File: plot_Posterior.py    From bayesfit with Apache License 2.0 6 votes vote down vote up
def plot_posterior(metrics):
    """Plots posterior surface for scale and slope parameters
    collapsing across guess and lapse rates.
    
    Keyword arguments:
    metrics -- contain important metrics about fitted model (dictionary)
    """
    # If other method other than numerical integration used, 
    # raise error 
    try: 
        metrics['posterior'] 
    except NameError: 
        raise ValueError('Posterior can only be plotted for numerical integration method (i.e., grid)')
    # Compute joint marginal posterior collapsing across nusiance 
    # parameters 
    posterior = np.sum(metrics['posterior'], axis = (2,3))
    # Generate plot of posterior with scale and 
    plt.contourf(metrics['Marginals_X']['scale'], 
                 metrics['Marginals_X']['slope'], 
                 posterior)
    plt.xlabel('scale', fontsize = 16)
    plt.ylabel('slope', fontsize = 16)
    plt.colorbar()
    plt.tight_layout()
    plt.show() 
Example #18
Source File: main.py    From svm-pytorch with MIT License 6 votes vote down vote up
def visualize(X, Y, model):
    W = model.weight.squeeze().detach().cpu().numpy()
    b = model.bias.squeeze().detach().cpu().numpy()

    delta = 0.001
    x = np.arange(X[:, 0].min(), X[:, 0].max(), delta)
    y = np.arange(X[:, 1].min(), X[:, 1].max(), delta)
    x, y = np.meshgrid(x, y)
    xy = list(map(np.ravel, [x, y]))

    z = (W.dot(xy) + b).reshape(x.shape)
    z[np.where(z > 1.0)] = 4
    z[np.where((z > 0.0) & (z <= 1.0))] = 3
    z[np.where((z > -1.0) & (z <= 0.0))] = 2
    z[np.where(z <= -1.0)] = 1

    plt.figure(figsize=(10, 10))
    plt.xlim([X[:, 0].min() + delta, X[:, 0].max() - delta])
    plt.ylim([X[:, 1].min() + delta, X[:, 1].max() - delta])
    plt.contourf(x, y, z, alpha=0.8, cmap="Greys")
    plt.scatter(x=X[:, 0], y=X[:, 1], c="black", s=10)
    plt.tight_layout()
    plt.show() 
Example #19
Source File: plot_boundary_on_data.py    From try-tf with Apache License 2.0 6 votes vote down vote up
def plot(X,Y,pred_func):
    # determine canvas borders
    mins = np.amin(X,0); 
    mins = mins - 0.1*np.abs(mins);
    maxs = np.amax(X,0); 
    maxs = maxs + 0.1*maxs;

    ## generate dense grid
    xs,ys = np.meshgrid(np.linspace(mins[0,0],maxs[0,0],300), 
            np.linspace(mins[0,1], maxs[0,1], 300));


    # evaluate model on the dense grid
    Z = pred_func(np.c_[xs.flatten(), ys.flatten()]);
    Z = Z.reshape(xs.shape)

    # Plot the contour and training examples
    plt.contourf(xs, ys, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=Y[:,1], s=50,
            cmap=colors.ListedColormap(['orange', 'blue']))
    plt.show() 
Example #20
Source File: utils.py    From plume with MIT License 6 votes vote down vote up
def plot_decision_boundary(pred_func, X, y, title=None):
    """分类器画图函数,可画出样本点和决策边界
    :param pred_func: predict函数
    :param X: 训练集X
    :param y: 训练集Y
    :return: None
    """

    # 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], s=40, c=y, cmap=plt.cm.Spectral)

    if title:
        plt.title(title)
    plt.show() 
Example #21
Source File: test_colorbar.py    From coffeegrindsize with 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
Source File: test_contour.py    From coffeegrindsize with 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
Source File: test_contour.py    From python3_ios with BSD 3-Clause "New" or "Revised" 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 #24
Source File: matplotlib_subplots.py    From livelossplot with MIT License 5 votes vote down vote up
def send(self, logger):
        Z = self._predict_pytorch(self.model, np.c_[self.xx.ravel(), self.yy.ravel()])[:, 1]
        Z = Z.reshape(self.xx.shape)
        plt.contourf(self.xx, self.yy, Z, cmap=self.cm_bg, alpha=.8)
        plt.scatter(self.X[:, 0], self.X[:, 1], c=self.Y, cmap=self.cm_points)
        if self.X_test is not None:
            plt.scatter(self.X_test[:, 0], self.X_test[:, 1], c=self.Y_test, cmap=self.cm_points, alpha=0.3) 
Example #25
Source File: test_colorbar.py    From coffeegrindsize with 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 #26
Source File: ABuMLExecute.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def plot_decision_boundary(pred_func, x, y):
    """
    通过x,y以构建meshgrid平面区域,要x矩阵特征列只有两个维度,在区域中使用外部传递的
    pred_func函数进行z轴的predict,通过contourf绘制特征平面区域,最后使用
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)在平面区域上填充原始特征
    点

    :param pred_func: callable函数,eg:pred_func: lambda p_x: fiter.predict(p_x), x, y
    :param x: 训练集x矩阵,numpy矩阵,需要特征列只有两个维度
    :param y: 训练集y序列,numpy序列
    """
    xlim = (x[:, 0].min() - 0.1, x[:, 0].max() + 0.1)
    ylim = (x[:, 1].min() - 0.1, x[:, 1].max() + 0.1)
    x_min, x_max = xlim
    y_min, y_max = ylim
    # 通过训练集中x的min和max,y的min,max构成meshgrid
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200),
                         np.linspace(y_min, y_max, 200))
    # 摊平xx,yy进行z轴的predict, pred_func: lambda p_x: fiter.predict(p_x), x, y
    z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    # z的shape跟随xx
    z = z.reshape(xx.shape)
    # 使用contourf绘制xx, yy, z,即特征平面区域以及z的颜色区别
    # noinspection PyUnresolvedReferences
    plt.contourf(xx, yy, z, cmap=plt.cm.Spectral)
    # noinspection PyUnresolvedReferences
    # 在特征区域的基础上将原始,两个维度使用scatter绘制以y为颜色的点
    plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)
    plt.show() 
Example #27
Source File: gd_algorithms_visualization.py    From neupy with MIT License 5 votes vote down vote up
def draw_countour(xgrid, ygrid, target_function):
    output = np.zeros((xgrid.shape[0], ygrid.shape[0]))

    for i, x in enumerate(xgrid):
        for j, y in enumerate(ygrid):
            output[j, i] = target_function(x, y)

    X, Y = np.meshgrid(xgrid, ygrid)

    plt.contourf(X, Y, output, 20, alpha=1, cmap='Blues')
    plt.colorbar() 
Example #28
Source File: overturning.py    From cosima-cookbook with Apache License 2.0 5 votes vote down vote up
def psi_avg(expts, n=10, clev=np.arange(-20,20,2)):
    
    if not isinstance(expts, list):
        expts = [expts]
        
    # computing
    results = []
    for expt in tqdm_notebook(expts, leave=False, desc='experiments'):
        psi_avg = cc.diagnostics.psi_avg(expt, n)
            
        result = {'psi_avg': psi_avg,
                  'expt': expt}
        results.append(result)
        
    IPython.display.clear_output()
   
    # plotting
    for result in results:
        psi_avg = result['psi_avg']
        expt = result['expt']
        
        plt.figure(figsize=(10, 5)) 
        plt.contourf(psi_avg.grid_yu_ocean, 
                 psi_avg.potrho, psi_avg, 
                 cmap=plt.cm.PiYG,levels=clev,extend='both')
        cb=plt.colorbar(orientation='vertical', shrink = 0.7)
    
        cb.ax.set_xlabel('Sv')
        plt.contour(psi_avg.grid_yu_ocean, psi_avg.potrho, psi_avg, levels=clev, colors='k', linewidths=0.25)
        plt.contour(psi_avg.grid_yu_ocean, psi_avg.potrho, psi_avg, levels=[0.0,], colors='k', linewidths=0.5)
        plt.gca().invert_yaxis()
    
        plt.ylim((1037.5,1034))
        plt.ylabel('Potential Density (kg m$^{-3}$)')
        plt.xlabel('Latitude ($^\circ$N)')
        plt.xlim([-75,85])
        plt.title('Overturning in %s' % expt) 
Example #29
Source File: test_contour.py    From twitter-stock-recommendation with 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 #30
Source File: test_contour.py    From twitter-stock-recommendation with 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))