Python matplotlib.pyplot.pcolormesh() Examples

The following are code examples for showing how to use matplotlib.pyplot.pcolormesh(). 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: phoneticSimilarity   Author: ronggong   File: baseline3_joint_GOP.py    GNU Affero General Public License v3.0 7 votes vote down vote up
def figurePlot(mfcc_line, vad_line):
    # plot Error analysis figures
    plt.figure(figsize=(16, 4))
    # plt.figure(figsize=(8, 4))
    # class weight
    ax1 = plt.subplot(211)
    y = np.arange(0, 80)
    x = np.arange(0, mfcc_line.shape[0]) * hopsize_t
    cax = plt.pcolormesh(x, y, np.transpose(mfcc_line[:, :, 7]))

    ax1.set_ylabel('Mel bands', fontsize=12)
    ax1.get_xaxis().set_visible(False)
    ax1.axis('tight')
    # plt.title('Calculating: '+rn+' phrase '+str(i_obs))

    ax2 = plt.subplot(212, sharex=ax1)
    x = np.arange(0, len(vad_line)) * hopsize_t
    ax2.plot(x, vad_line)
    ax2.set_ylabel('VAD', fontsize=12)
    ax2.axis('tight')
    plt.show() 
Example 2
Project: aftershoq   Author: mfranckie   File: ndtestfunc.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def plt(self, x = None, y = None, cmin= None, cmax=None, cmap = 'hot'):

        if x is None:
            x = np.linspace(0,1)
        if y is None and self.ND > 1:
            y = np.linspace(0,1)

        z = []

        if self.ND > 1:
            coord = []
            for i in range(self.ND):
                coord.append(0.)
            for xx in x:
                row = []
                coord[1] = xx
                for yy in y:
                    coord[0] = yy
                    row.append(self.testfunc(coord))
                z.append(row)

        #pl.contour(x,y,z)
        pl.pcolormesh(x,y,z,vmin=cmin, vmax=cmax, cmap=cmap)
        cbar = pl.colorbar()
        return cbar 
Example 3
Project: Fundamentals-of-Machine-Learning-with-scikit-learn   Author: PacktPublishing   File: 1logistic_regression.py    MIT License 6 votes vote down vote up
def show_classification_areas(X, Y, lr):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(30, 25))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm)
    plt.xlabel('X')
    plt.ylabel('Y')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show() 
Example 4
Project: residual-flows   Author: rtqichen   File: visualize_flow.py    MIT License 6 votes vote down vote up
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
    """
    Args:
        potential: computes U(z_k) given z_k
    """
    xside = np.linspace(LOW, HIGH, npts)
    yside = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(xside, yside)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.Tensor(z)
    u = potential(z).cpu().numpy()
    p = np.exp(-u).reshape(npts, npts)

    plt.pcolormesh(xx, yy, p)
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example 5
Project: Speech-Recognition   Author: ncble   File: test_cma_lu.py    Apache License 2.0 6 votes vote down vote up
def draw_surface_level(fun, centre = np.zeros(2), taille = 1.0, message = None):

		plt.figure(figsize=(5, 3))
		axes = plt.gca()
		if message:
			plt.title(message)
		x_min, y_min = (centre - taille)#[0,0], (centre - taille)[0,1]  #X[:, 0].min()
		x_max, y_max = (centre + taille)#[0,0], (centre + taille)[0,1]     #X[:, 0].max()
		
		axes.set_xlim([x_min,x_max])
		axes.set_ylim([y_min,y_max])
		XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]

		Z = fun(np.c_[XX.ravel(), YY.ravel()])

		# Put the result into a color plot
		Z = Z.reshape(XX.shape)
		plt.pcolormesh(XX, YY, Z, cmap = plt.cm.jet)
		# CS = plt.contour(XX, YY, Z, cmap = plt.cm.jet)
		# plt.clabel(CS, fmt='%2.1f', colors='b', fontsize=14)
		plt.show() 
Example 6
Project: vibe   Author: 3ll3d00d   File: graphs.py    MIT License 6 votes vote down vote up
def showSpectro(self):
        # measurementPath = 'C:\\Users\\\Matt\\OneDrive\\Documents\\eot\\Edge of Tomorrow - Opening.wav'
        measurementPath = os.path.join(os.path.dirname(__file__), 'data', 'eot.wav')
        measurement = ms.loadSignalFromWav(measurementPath)

        # t, f, Sxx_spec = measurement.spectrogram()
        # plt.pcolormesh(f, t, Sxx_spec)
        # plt.ylim(0, 160)
        cmap = plt.get_cmap('viridis')
        cmap.set_under(color='k', alpha=None)
        plt.specgram(measurement.samples,
                     NFFT=measurement.getSegmentLength(),
                     Fs=measurement.fs,
                     detrend=mlab.detrend_none,
                     mode='magnitude',
                     noverlap=measurement.getSegmentLength() / 2,
                     window=mlab.window_hanning,
                     vmin=-60,
                     cmap=plt.cm.gist_heat)
        plt.ylim(0, 100)
        plt.show() 
Example 7
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.hypot(X, Y) / 5
    Z = (Z - Z.min()) / Z.ptp()

    # The color array can include masked values:
    Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)

    fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
    ax1.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')
    ax2.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])
    ax3.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 9
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.sqrt(X**2 + Y**2)/5

    _, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.pcolormesh(y, x, Z)
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z.T)
    with pytest.raises(TypeError):
        ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud")
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud")
    x[0] = np.NaN
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1])
    with np.errstate(invalid='ignore'):
        x = np.ma.array(x, mask=(x < 0))
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1]) 
Example 10
Project: ParticleFlowBayesRule   Author: xinshi-chen   File: visualize_flow.py    MIT License 6 votes vote down vote up
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
    """
    Args:
        potential: computes U(z_k) given z_k
    """
    xside = np.linspace(LOW, HIGH, npts)
    yside = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(xside, yside)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.Tensor(z)
    u = potential(z).cpu().numpy()
    p = np.exp(-u).reshape(npts, npts)

    plt.pcolormesh(xx, yy, p)
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example 11
Project: seq2seq-summarizer   Author: ymfa   File: utils.py    MIT License 6 votes vote down vote up
def show_attention_map(src_words, pred_words, attention, pointer_ratio=None):
  fig, ax = plt.subplots(figsize=(16, 4))
  im = plt.pcolormesh(np.flipud(attention), cmap="GnBu")
  # set ticks and labels
  ax.set_xticks(np.arange(len(src_words)) + 0.5)
  ax.set_xticklabels(src_words, fontsize=14)
  ax.set_yticks(np.arange(len(pred_words)) + 0.5)
  ax.set_yticklabels(reversed(pred_words), fontsize=14)
  if pointer_ratio is not None:
    ax1 = ax.twinx()
    ax1.set_yticks(np.concatenate([np.arange(0.5, len(pred_words)), [len(pred_words)]]))
    ax1.set_yticklabels('%.3f' % v for v in np.flipud(pointer_ratio))
    ax1.set_ylabel('Copy probability', rotation=-90, va="bottom")
  # let the horizontal axes labelling appear on top
  ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
  # rotate the tick labels and set their alignment
  plt.setp(ax.get_xticklabels(), rotation=-45, ha="right", rotation_mode="anchor") 
Example 12
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.sqrt(X**2 + Y**2)/5
    Z = (Z - Z.min()) / (Z.max() - Z.min())

    # The color array can include masked values:
    Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z)

    fig = plt.figure()
    ax = fig.add_subplot(131)
    ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')

    ax = fig.add_subplot(132)
    ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])

    ax = fig.add_subplot(133)
    ax.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example 13
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 14
Project: RSV   Author: Healthcast   File: skeleton.py    GNU General Public License v2.0 6 votes vote down vote up
def test_knn():
    iris = datasets.load_iris()
    iris_X = iris.data[:,:2]
    iris_y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=.5, \
                                                        random_state=0)
    #n: number of neighbors
    #weights: uniform or distance
    clf = neighbors.KNeighborsClassifier(15, weights='uniform')
    clf.fit(X_train, y_train)
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)

    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"%(15, 'uniform'))
    plt.show() 
Example 15
Project: RSV   Author: Healthcast   File: skeleton.py    GNU General Public License v2.0 6 votes vote down vote up
def test_knn():
    iris = datasets.load_iris()
    iris_X = iris.data[:,:2]
    iris_y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=.5, \
                                                        random_state=0)
    #n: number of neighbors
    #weights: uniform or distance
    clf = neighbors.KNeighborsClassifier(15, weights='uniform')
    clf.fit(X_train, y_train)
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)

    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"%(15, 'uniform'))
    plt.show() 
Example 16
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 6 votes vote down vote up
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options):
    """Makes a pseudocolor plot.
    
    xs:
    ys:
    zs:
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    X, Y = np.meshgrid(xs, ys)
    Z = zs

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)

    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10) 
Example 17
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.hypot(X, Y) / 5
    Z = (Z - Z.min()) / Z.ptp()

    # The color array can include masked values:
    Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)

    fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
    ax1.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')
    ax2.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])
    ax3.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example 18
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 19
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.sqrt(X**2 + Y**2)/5

    _, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.pcolormesh(y, x, Z)
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z.T)
    with pytest.raises(TypeError):
        ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud")
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud")
    x[0] = np.NaN
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1])
    with np.errstate(invalid='ignore'):
        x = np.ma.array(x, mask=(x < 0))
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1]) 
Example 20
Project: simple-linear-classification   Author: williamd4112   File: plot.py    MIT License 6 votes vote down vote up
def plot_decision_boundary(func, x_, t_, x_min, y_min, x_max, y_max, h):
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    
    Z = func(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(4, 3))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

    # Plot also the training points
    plt.scatter(x_[:, 0], x_[:, 1], c=t_, edgecolors='k', cmap=plt.cm.Paired)
    plt.xlabel('x1')
    plt.ylabel('x2')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show() 
Example 21
Project: monsoon-onset   Author: jenfly   File: momentum-budget.py    MIT License 6 votes vote down vote up
def pcolor_sector(var, daynm, clims, u=None, v=None):
        days = var[daynm].values
        lat = atm.get_coord(var, 'lat')
        x, y = np.meshgrid(days, lat)
        vals = var.values.T
        vals = np.ma.masked_array(vals, mask=np.isnan(vals))
        plt.pcolormesh(x, y, vals, cmap='RdBu_r')
        plt.clim(clims)
        plt.colorbar(extend='both')
        if u is not None:
            plt.contour(x, y, u.values.T, [0], colors='k', linewidths=1.5)
        if v is not None:
            plt.contour(x, y, v.values.T, [0], colors='k', alpha=0.5)
        plt.xlim(days.min(), days.max())
        plt.xlabel('Rel Day')
        plt.ylabel('Latitude') 
Example 22
Project: Machine-Learning-Algorithms-Second-Edition   Author: PacktPublishing   File: logistic_regression.py    MIT License 6 votes vote down vote up
def show_classification_areas(X, Y, lr):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(30, 25))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm)
    plt.xlabel('X')
    plt.ylabel('Y')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show() 
Example 23
Project: randomforest-density-python   Author: ksanjeevan   File: df_help.py    MIT License 6 votes vote down vote up
def check_plot(self):

        X = self.grid[0]
        Y = self.grid[1]
        Z = self.dist
        
        fig = plt.figure(figsize=(12, 12))
        ax = fig.add_subplot(111)
   
        vmin = np.min(Z)
        vmax = np.max(Z)
        var = plt.pcolormesh(np.array(X),np.array(Y),np.array(Z), cmap=cm.Greens, vmin=vmin, vmax=vmax)
        plt.colorbar(var, ticks=np.arange(vmin, vmax, (vmax-vmin)/8))
        ax = plt.gca()
        gris = 200.0
        ax.set_facecolor((gris/255, gris/255, gris/255))
        
        ax.scatter(*zip(*self.data), alpha=.5, c='k', s=10., lw=0)

        plt.xlim(np.min(X), np.max(X))
        plt.ylim(np.min(Y), np.max(Y))
        plt.grid()
        fig.savefig('true_dist_check.png', format='png')
        plt.close() 
Example 24
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.sqrt(X**2 + Y**2)/5
    Z = (Z - Z.min()) / (Z.max() - Z.min())

    # The color array can include masked values:
    Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z)

    fig = plt.figure()
    ax = fig.add_subplot(131)
    ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')

    ax = fig.add_subplot(132)
    ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])

    ax = fig.add_subplot(133)
    ax.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example 25
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example 26
Project: bird-species-classification   Author: johnmartinsson   File: vis.py    MIT License 6 votes vote down vote up
def plot_sound_class_by_decending_accuracy(experiment_path):
    config_parser = configparser.ConfigParser()
    config_parser.read(os.path.join(experiment_path, "conf.ini"))
    model_name = config_parser['MODEL']['ModelName']
    y_trues, y_scores = load_predictions(experiment_path)

    y_true = [np.argmax(y_t) for y_t in y_trues]
    y_pred = [np.argmax(y_s) for y_s in y_scores]

    confusion_matrix = metrics.confusion_matrix(y_true, y_pred)

    accuracies = []
    (nb_rows, nb_cols) = confusion_matrix.shape
    for i in range(nb_rows):
        accuracy = confusion_matrix[i][i] / np.sum(confusion_matrix[i,:])
        accuracies.append(accuracy)

    fig = plt.figure()
    plt.title("Sound Class ranked by Accuracy ({})".format(model_name))
    plt.plot(sorted(accuracies, reverse=True))
    plt.ylabel("Accuracy")
    plt.xlabel("Rank")
    # plt.pcolormesh(confusion_matrix, cmap=cmap)
    fig.savefig(os.path.join(experiment_path, "descending_accuracy.png")) 
Example 27
Project: DiscEvolution   Author: rbooth200   File: plot_R-t.py    GNU General Public License v3.0 5 votes vote down vote up
def pcolor_plot(x,y,z, **kwargs):
    ax = plt.gca()
    plt.pcolormesh(x,y,z, **kwargs)
    ax.format_coord = Formatter(x,y,z) 
Example 28
Project: DataSciUF-Tutorial-Student   Author: jdamiani27   File: class_vis.py    MIT License 5 votes vote down vote up
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 10.5
    y_min = 0.0; y_max = 10.5
    
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==2]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==2]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==4]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==4]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="benign")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="malignant")
    plt.legend()
    plt.xlabel("uniformity_cell_shape")
    plt.ylabel("bare_nuclei")

    plt.savefig("test.png") 
Example 29
Project: optics   Author: radiasoft   File: bending_magnet_srw1.py    Apache License 2.0 5 votes vote down vote up
def main():
    """test bending magnet and plot results"""
    res = test_bending_magnet_infrared()
    pkdc('Calling plots with array shape: {}...', res.intensity.shape)
    plt.pcolormesh(res.dim_x, res.dim_y, res.intensity.transpose())
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 30
Project: optics   Author: radiasoft   File: bending_magnet_srw_param1.py    Apache License 2.0 5 votes vote down vote up
def main():
    wavefront = test_simulation()
    mesh = copy.deepcopy(wavefront.mesh)
    intensity = pkarray.new_float([0] * mesh.nx * mesh.ny)
    srw.srwl.CalcIntFromElecField(intensity, wavefront, 6, 1, 3, mesh.eStart, 0, 0)
    import matplotlib.pyplot as plt
    dim_x = np.linspace(mesh.xStart, mesh.xFin, mesh.nx)
    dim_y = np.linspace(mesh.yStart, mesh.yFin, mesh.ny)
    intensity = np.array(intensity).reshape((mesh.ny,mesh.nx))
    plt.pcolormesh(dim_x, dim_y, intensity)
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 31
Project: optics   Author: radiasoft   File: bending_magnet_srw_native1.py    Apache License 2.0 5 votes vote down vote up
def main():
    wfr = test_simulation()
    mesh = copy.deepcopy(wfr.mesh)
    arI1s = pkarray.new_float([0] * mesh.nx * mesh.ny)
    srw.srwl.CalcIntFromElecField(arI1s, wfr, 6, 1, 3, mesh.eStart, 0, 0)
    import matplotlib.pyplot as plt
    dim_x = np.linspace(mesh.xStart, mesh.xFin, mesh.nx)
    dim_y = np.linspace(mesh.yStart, mesh.yFin, mesh.ny)
    intensity = np.array(arI1s).reshape((mesh.ny,mesh.nx))
    plt.pcolormesh(dim_x, dim_y, intensity)
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 32
Project: TopoMetricUncertainty   Author: UP-RS-ESP   File: surfaces.py    MIT License 5 votes vote down vote up
def main():
    from matplotlib import pyplot as pl

    xb, yb, z = gaussian_hill_dem(0.1)
    pl.pcolormesh(xb, yb, z)
    pl.colorbar()
    pl.show()

    xb, yb, z = sphere_dem(0.1)
    z = np.ma.masked_invalid(z)
    pl.pcolormesh(xb, yb, z)
    pl.colorbar()
    pl.show() 
Example 33
Project: pykaldi   Author: pykaldi   File: compute-vad.py    Apache License 2.0 5 votes vote down vote up
def show_plot(
    key, segment_times, sample_freqs, spec, duration, wav_data, vad_feat
):
    """This function plots the vad against the signal and the spectrogram.

    Args:
        segment_times: the time intervals acting as the x axis
        sample_freqs: the frequency bins acting as the y axis
        spec: the spectrogram
        duration: duration of the wave file
        wav_data: the wave data
        vad_feat: VAD features
    """

    import matplotlib.pyplot as plt
    import matplotlib.mlab as mlb

    plt.subplot(3, 1, 1)
    plt.pcolormesh(segment_times, sample_freqs, 10 * np.log10(spec), cmap="jet")
    plt.ylabel("Frequency [Hz]")
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 2)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, wav_data.shape[0])
    plt.plot(tmp_axis, wav_data / np.abs(np.max(wav_data)))
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 3)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, vad_feat.shape[0])
    plt.plot(tmp_axis, vad_feat)
    plt.xlabel("Time [sec]")

    plt.savefig("plots/" + key, bbox_inches="tight") 
Example 34
Project: StanShock   Author: IhmeGroup   File: stanShock.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotXTDiagram(self,XTDiagram,limits=None):
        '''
        Method: plotXTDiagram
        --------------------------------------------------------------------------
        This method creates a contour plot of the XTDiagram data
            inputs:
                XTDiagram=XTDiagram object; obtained from the XTDiagrams dictionary
                limits = tuple of maximum and minimum for the pcolor (vMin,vMax)
                
        '''
        plt.figure()
        t = [t*1000.0 for t in XTDiagram.t]
        X, T = np.meshgrid(XTDiagram.x,t)
        variableMatrix = np.zeros(X.shape)
        for k, variablek in enumerate(XTDiagram.variable): 
            variableMatrix[k,:]=variablek
        variable=XTDiagram.name
        if variable in ["density","r","rho"]:
            plt.title("$\\rho\ [\mathrm{kg/m^3}]$")
        elif variable in ["velocity","u"]:
            plt.title("$u\ [\mathrm{m/s}]$")
        elif variable in ["pressure","p"]:
            variableMatrix /= 1.0e5 #convert to bar
            plt.title("$p\ [\mathrm{bar}]$")
        elif variable in ["temperature","t"]:
            plt.title("$T\ [\mathrm{K}]$")
        elif variable in ["gamma","g","specific heat ratio", "heat capacity ratio"]:
            plt.title("$\gamma$")
        else: plt.title("$\mathrm{"+variable+"}$")
        if limits is None: plt.pcolormesh(X,T,variableMatrix,cmap='jet')
        else: plt.pcolormesh(X,T,variableMatrix,cmap='jet',vmin=limits[0],vmax=limits[1])
        plt.xlabel("$x\ [\mathrm{m}]$")
        plt.ylabel("$t\ [\mathrm{ms}]$")
        plt.axis([min(XTDiagram.x), max(XTDiagram.x), min(t), max(t)])
        plt.colorbar()
############################################################################## 
Example 35
Project: residual-flows   Author: rtqichen   File: visualize_flow.py    MIT License 5 votes vote down vote up
def plt_flow(prior_logdensity, transform, ax, npts=100, title="$q(x)$", device="cpu"):
    """
    Args:
        transform: computes z_k and log(q_k) given z_0
    """
    side = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(side, side)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.tensor(z, requires_grad=True).type(torch.float32).to(device)
    logqz = prior_logdensity(z)
    logqz = torch.sum(logqz, dim=1)[:, None]
    z, logqz = transform(z, logqz)
    logqz = torch.sum(logqz, dim=1)[:, None]

    xx = z[:, 0].cpu().numpy().reshape(npts, npts)
    yy = z[:, 1].cpu().numpy().reshape(npts, npts)
    qz = np.exp(logqz.cpu().numpy()).reshape(npts, npts)

    plt.pcolormesh(xx, yy, qz)
    ax.set_xlim(LOW, HIGH)
    ax.set_ylim(LOW, HIGH)
    cmap = matplotlib.cm.get_cmap(None)
    ax.set_facecolor(cmap(0.))
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example 36
Project: more   Author: ngupta23   File: plot_similarity.py    MIT License 5 votes vote down vote up
def plot_similarity(data,
                    y,
                    sample=True,
                    frac=1.0,
                    random_state=1,
                    figsize=None):
    """
    data: Dataframe to plot
    y: Column to sort the data by before computing similarity
       (usually the output)
    sample: (Default = True) Should the data be sampled.
            Advisable for larger darasets otherewise it takes a long time
    frac = (Default = 1.0 --> Take full dataset)
            What fraction of the data should be sampled
    """
    sns.set(rc={'image.cmap': 'cubehelix'})
    # get a subset of the data, and normalize it
    if (sample is True):
        df_sub = data.sample(frac=frac, replace=False,
                             random_state=random_state)
    df_normalized = (df_sub-df_sub.mean())/(df_sub.std())
    df_sorted = df_normalized.sort_values(by=y)
    Y = distance.pdist(df_sorted, "euclidean")
    A = distance.squareform(Y)
    S = 0.5/(1+np.exp(A))  # convert from distance to similarity
    # plot the similarity matrix using seaborn color utilities

    plt.figure(figsize=figsize)
    plt.pcolormesh(S)
    plt.colorbar() 
Example 37
Project: more   Author: ngupta23   File: plot_similarity.py    MIT License 5 votes vote down vote up
def plot_similarity(data,
                    y,
                    sample=True,
                    frac=1.0,
                    random_state=1,
                    figsize=None):
    """
    data: Dataframe to plot
    y: Column to sort the data by before computing similarity
       (usually the output)
    sample: (Default = True) Should the data be sampled.
            Advisable for larger darasets otherewise it takes a long time
    frac = (Default = 1.0 --> Take full dataset)
            What fraction of the data should be sampled
    """
    sns.set(rc={'image.cmap': 'cubehelix'})
    # get a subset of the data, and normalize it
    if (sample is True):
        df_sub = data.sample(frac=frac, replace=False,
                             random_state=random_state)
    df_normalized = (df_sub-df_sub.mean())/(df_sub.std())
    df_sorted = df_normalized.sort_values(by=y)
    Y = distance.pdist(df_sorted, "euclidean")
    A = distance.squareform(Y)
    S = 0.5/(1+np.exp(A))  # convert from distance to similarity
    # plot the similarity matrix using seaborn color utilities

    plt.figure(figsize=figsize)
    plt.pcolormesh(S)
    plt.colorbar() 
Example 38
Project: Harvard-PH526x   Author: LamaHamadeh   File: kNN_Classification.py    MIT License 5 votes vote down vote up
def plot_prediction_grid (xx, yy, prediction_grid, filename):
    """ Plot KNN predictions for every point on the grid."""
    from matplotlib.colors import ListedColormap
    background_colormap = ListedColormap (["hotpink","lightskyblue", "yellowgreen"])
    observation_colormap = ListedColormap (["red","blue","green"])
    plt.figure(figsize =(10,10))
    plt.pcolormesh(xx, yy, prediction_grid, cmap = background_colormap, alpha = 0.5)
    plt.scatter(predictors[:,0], predictors [:,1], c = outcomes, cmap = observation_colormap, s = 50)
    plt.xlabel('Variable 1'); plt.ylabel('Variable 2')
    plt.xticks(()); plt.yticks(())
    plt.xlim (np.min(xx), np.max(xx))
    plt.ylim (np.min(yy), np.max(yy))
    plt.savefig(filename) 
Example 39
Project: Identificador-Fraude-Enron   Author: luisneto98   File: class_vis.py    MIT License 5 votes vote down vote up
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 1.0
    y_min = 0.0; y_max = 1.0
    
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="fast")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="slow")
    plt.legend()
    plt.xlabel("bumpiness")
    plt.ylabel("grade")

    plt.savefig("test.png") 
Example 40
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pandas_pcolormesh(pd):
    time = pd.date_range('2000-01-01', periods=10)
    depth = np.arange(20)
    data = np.random.rand(20, 10)

    fig, ax = plt.subplots()
    ax.pcolormesh(time, depth, data) 
Example 41
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_zoom_inset():
    dx, dy = 0.05, 0.05
    # generate 2 2d grids for the x & y bounds
    y, x = np.mgrid[slice(1, 5 + dy, dy),
                    slice(1, 5 + dx, dx)]
    z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)

    fig, ax = plt.subplots()
    ax.pcolormesh(x, y, z)
    ax.set_aspect(1.)
    ax.apply_aspect()
    # we need to apply_aspect to make the drawing below work.

    # Make the inset_axes...  Position axes co-ordinates...
    axin1 = ax.inset_axes([0.7, 0.7, 0.35, 0.35])
    # redraw the data in the inset axes...
    axin1.pcolormesh(x, y, z)
    axin1.set_xlim([1.5, 2.15])
    axin1.set_ylim([2, 2.5])
    axin1.set_aspect(ax.get_aspect())

    rec, connectors = ax.indicate_inset_zoom(axin1)
    fig.canvas.draw()
    xx = np.array([[1.5,  2.],
                   [2.15, 2.5]])
    assert(np.all(rec.get_bbox().get_points() == xx))
    xx = np.array([[0.6325, 0.692308],
                   [0.8425, 0.907692]])
    np.testing.assert_allclose(axin1.get_position().get_points(),
            xx, rtol=1e-4) 
Example 42
Project: musical-onset-efficient   Author: ronggong   File: plot_code.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_schluter(mfcc,
                  obs_i,
                  hopsize_t,
                  groundtruth_onset,
                  detected_onsets):

    plt.figure(figsize=(16, 6))

    ax1 = plt.subplot(2, 1, 1)
    y = np.arange(0, 80)
    x = np.arange(0, mfcc.shape[0]) * hopsize_t
    plt.pcolormesh(x, y, np.transpose(mfcc[:, 80 * 10:80 * 11]))
    for i_gs, gs in enumerate(groundtruth_onset):
        plt.axvline(gs, color='r', linewidth=2)

    ax1.set_ylabel('Mel bands', fontsize=12)
    ax1.get_xaxis().set_visible(False)
    ax1.axis('tight')

    ax2 = plt.subplot(212, sharex=ax1)
    plt.plot(np.arange(0, len(obs_i)) * hopsize_t, obs_i)
    for i_do, do in enumerate(detected_onsets):
        plt.axvline(do, color='r', linewidth=2)

    ax2.set_ylabel('ODF', fontsize=12)
    ax2.axis('tight')
    plt.xlabel('time (s)')
    plt.show() 
Example 43
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: rover_utils.py    MIT License 5 votes vote down vote up
def plot_2d_rover(roverdomain, ngrid_points=100, ntraj_points=100, colormap='RdBu', draw_colorbar=False):
    import matplotlib.pyplot as plt
    # get a grid of points over the state space
    points = [np.linspace(mi, ma, ngrid_points, endpoint=True) for mi, ma in zip(*roverdomain.s_range)]
    grid_points = np.meshgrid(*points)
    points = np.hstack([g.reshape((-1, 1)) for g in grid_points])

    # compute the cost at each point on the grid
    costs = roverdomain.cost_fn(points)

    # get the cost of the current trajectory
    traj_cost = roverdomain.estimate_cost()

    # get points on the current trajectory
    traj_points = roverdomain.traj.get_points(np.linspace(0., 1.0, ntraj_points, endpoint=True))

    # set title to be the total cost
    plt.title('traj cost: {0}'.format(traj_cost))
    print('traj cost: {0}'.format(traj_cost))
    # plot cost function
    cmesh = plt.pcolormesh(grid_points[0], grid_points[1], costs.reshape((ngrid_points, -1)), cmap=colormap)
    if draw_colorbar:
        plt.gcf().colorbar(cmesh)
    # plot traj
    plt.plot(traj_points[:, 0], traj_points[:, 1], 'g')
    # plot start and goal
    plt.plot([roverdomain.start[0], roverdomain.goal[0]], (roverdomain.start[1], roverdomain.goal[1]), 'ok')

    return cmesh 
Example 44
Project: ParticleFlowBayesRule   Author: xinshi-chen   File: visualize_flow.py    MIT License 5 votes vote down vote up
def plt_flow(prior_logdensity, transform, ax, npts=100, title="$q(x)$", device="cpu"):
    """
    Args:
        transform: computes z_k and log(q_k) given z_0
    """
    side = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(side, side)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.tensor(z, requires_grad=True).type(torch.float32).to(device)
    logqz = prior_logdensity(z)
    logqz = torch.sum(logqz, dim=1)[:, None]
    z, logqz = transform(z, logqz)
    logqz = torch.sum(logqz, dim=1)[:, None]

    xx = z[:, 0].cpu().numpy().reshape(npts, npts)
    yy = z[:, 1].cpu().numpy().reshape(npts, npts)
    qz = np.exp(logqz.cpu().numpy()).reshape(npts, npts)

    plt.pcolormesh(xx, yy, qz)
    ax.set_xlim(LOW, HIGH)
    ax.set_ylim(LOW, HIGH)
    cmap = matplotlib.cm.get_cmap(None)
    ax.set_facecolor(cmap(0.))
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example 45
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.sqrt(X**2 + Y**2)/5

    _, ax = plt.subplots()
    assert_raises(TypeError, ax.pcolormesh, y, x, Z)
    assert_raises(TypeError, ax.pcolormesh, X, Y, Z.T)
    assert_raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1],
                  shading="gouraud")
    assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1],
                  shading="gouraud") 
Example 46
Project: neural-network-animation   Author: miloharper   File: test_colors.py    MIT License 5 votes vote down vote up
def test_cmap_and_norm_from_levels_and_colors():
    data = np.linspace(-2, 4, 49).reshape(7, 7)
    levels = [-1, 2, 2.5, 3]
    colors = ['red', 'green', 'blue', 'yellow', 'black']
    extend = 'both'
    cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)

    ax = plt.axes()
    m = plt.pcolormesh(data, cmap=cmap, norm=norm)
    plt.colorbar(m)

    # Hide the axes labels (but not the colorbar ones, as they are useful)
    for lab in ax.get_xticklabels() + ax.get_yticklabels():
        lab.set_visible(False) 
Example 47
Project: RSV   Author: Healthcast   File: skeleton.py    GNU General Public License v2.0 5 votes vote down vote up
def test_RF():
    
    iris = datasets.load_iris()
    iris_X = iris.data[:,:2]
    iris_y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=.5, \
                                                        random_state=0)
    #test max_depth: the max depth of the tree
    #test n_estimators: how many trees used
    #test max_features: how many good features used in each split
    clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1)
    clf.fit(X_train, y_train)
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)


    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"%(15, 'uniform'))
    plt.show() 
Example 48
Project: RSV   Author: Healthcast   File: skeleton.py    GNU General Public License v2.0 5 votes vote down vote up
def test_RF():
    
    iris = datasets.load_iris()
    iris_X = iris.data[:,:2]
    iris_y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=.5, \
                                                        random_state=0)
    #test max_depth: the max depth of the tree
    #test n_estimators: how many trees used
    #test max_features: how many good features used in each split
    clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1)
    clf.fit(X_train, y_train)
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1

    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)


    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"%(15, 'uniform'))
    plt.show() 
Example 49
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 5 votes vote down vote up
def Contour(obj, pcolor=False, contour=True, imshow=False, **options):
    """Makes a contour plot.
    
    d: map from (x, y) to z, or object that provides GetDict
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    imshow: boolean, whether to use plt.imshow
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    try:
        d = obj.GetDict()
    except AttributeError:
        d = obj

    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    xs, ys = zip(*d.keys())
    xs = sorted(set(xs))
    ys = sorted(set(ys))

    X, Y = np.meshgrid(xs, ys)
    func = lambda x, y: d.get((x, y), 0)
    func = np.vectorize(func)
    Z = func(X, Y)

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)
    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10)
    if imshow:
        extent = xs[0], xs[-1], ys[0], ys[-1]
        plt.imshow(Z, extent=extent, **options) 
Example 50
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pandas_pcolormesh(pd):
    time = pd.date_range('2000-01-01', periods=10)
    depth = np.arange(20)
    data = np.random.rand(20, 10)

    fig, ax = plt.subplots()
    ax.pcolormesh(time, depth, data)