Python matplotlib.pyplot.clim() Examples

The following are code examples for showing how to use matplotlib.pyplot.clim(). 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: pohmm-keystroke   Author: vmonaco   File: plotting.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_stationarity_examples(m, names):
    import matplotlib.cm as cm

    def plot_fn(ax, i):
        plt.grid(False)
        plt.imshow(m[i], origin='lower', interpolation='none', cmap=cm.Greys,
                   extent=[0.5, m[i].shape[0] + 0.5, 0.5, m[i].shape[1] + 0.5])

        ax.set_xticks(np.arange(1, m[i].shape[0] + 1))
        ax.set_yticks(np.arange(1, m[i].shape[1] + 1))

        plt.clim(m[i].values.mean() - 4 * m[i].values.std(), m[i].values.mean() + 4 * m[i].values.std())
        ax.text(0.5, 0.95, names[i], va='top', ha='center', transform=ax.transAxes, color='black', fontsize=15)
        return

    return plot6(plot_fn, xlabel='Train sample', ylabel='Predict sample') 
Example 2
Project: neurips19-graph-protein-design   Author: jingraham   File: seq_only_train.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 3
Project: neurips19-graph-protein-design   Author: jingraham   File: test_redesign.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(axis=u'both', which=u'both',length=0, labelsize=5)
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 4
Project: neurips19-graph-protein-design   Author: jingraham   File: utils.py    MIT License 6 votes vote down vote up
def plot_log_probs(log_probs, total_step, folder=''):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(folder + 'probs{}.pdf'.format(total_step))
    return 
Example 5
Project: neurips19-graph-protein-design   Author: jingraham   File: seq_only_test.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 6
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_att_maps_epoch.py    MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Epochs 
Example 7
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_fmaps.py    MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Load options 
Example 8
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()
    plt.suptitle(title) 
Example 9
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    MIT License 6 votes vote down vote up
def plotNNFilterOverlay(input_im, units, figure_id, interp='bilinear',
                        colormap=cm.jet, colormap_lim=None, title='', alpha=0.8):
    plt.ion()
    filters = units.shape[2]
    fig = plt.figure(figure_id, figsize=(5,5))
    fig.clf()

    for i in range(filters):
        plt.imshow(input_im[:,:,0], interpolation=interp, cmap='gray')
        plt.imshow(units[:,:,i], interpolation=interp, cmap=colormap, alpha=alpha)
        plt.axis('off')
        plt.colorbar()
        plt.title(title, fontsize='small')
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

    # plt.savefig('{}/{}.png'.format(dir_name,time.time()))




## Load options 
Example 10
Project: sleep-convolutions-tf   Author: cliffordlab   File: crossval.py    MIT License 6 votes vote down vote up
def plot_mats(df, title_prefix=None):
    title = 'Training set'
    if title_prefix is not None:
        title = title_prefix+', '+title
    DF = df[df.testset == False]
    plt.figure(figsize=(15, 6))
    plt.subplot(121)
    cm = metrics.confusion_matrix(DF.truth, DF.prediction)
    plot_confusion_matrix(cm, labels, normalize=True, title=title)
    plt.clim(0, 1)

    DF = df[df.testset == True]
    plt.subplot(122)
    cm = metrics.confusion_matrix(DF.truth, DF.prediction)
    plot_confusion_matrix(cm, labels, normalize=True, title='Test set')
    plt.clim(0, 1)
    plt.tight_layout()
    return 
Example 11
Project: sleep-convolutions-tf   Author: cliffordlab   File: crossval.py    MIT License 6 votes vote down vote up
def plot_mats_reduced(df, title_prefix=None):
    title = 'Training set'
    if title_prefix is not None:
        title = title_prefix+', '+title
    DF = df[df.testset == False]
    plt.figure(figsize=(15, 6))
    plt.subplot(121)
    cm = metrics.confusion_matrix(reduce_stages(DF.truth), reduce_stages(DF.prediction))
    plot_confusion_matrix(cm, reduced_labels, normalize=True, title=title)
    plt.clim(0, 1)

    DF = df[df.testset == True]
    plt.subplot(122)
    cm = metrics.confusion_matrix(reduce_stages(DF.truth), reduce_stages(DF.prediction))
    plot_confusion_matrix(cm, reduced_labels, normalize=True, title='Test set')
    plt.clim(0, 1)
    plt.tight_layout()
    return 
Example 12
Project: elastic_benchmarks   Author: ManuelMBaumann   File: elast_wedge.py    MIT License 6 votes vote down vote up
def makeplots( domain, geom, Lx, Lz, value, name, title, ndigits=0, index=None, clim=None, lineOn=False, imgtype=None,):
  points, colors = domain.elem_eval( [ geom, value ], ischeme='bezier3', separate=True )

  with plot.PyPlot( name, ndigits=ndigits, figsize=(5,6), index=index, imgtype=imgtype ) as plt:
    plt.mesh( points, colors, triangulate='bezier', edgecolors='none' )
    plt.title(title)
    plt.xlabel('x [m]')
    plt.ylabel('z [m]')

    plt.xticks( [0, Lx/2.0, Lx], ['0', '300', '600'] )
    plt.yticks( [-0, -0.4*Lz, -0.8*Lz, -Lz], ['0', '400', '800', '1000'] )

    if clim is not None:
      plt.clim(*clim)
    plt.colorbar()

    if lineOn:
      # Only for wedge problem in 2D
      plt.plot( [0, 600],[-400, -500],'k' )
      plt.plot( [0, 600],[-800, -600],'k' ) 
Example 13
Project: pypiv   Author: jr7   File: test_adaptive_piv.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    imgs = glob('images/real_ana_finger*')
    frames = [plt.imread(x) for x in imgs]

    frame_a = frames[0]
    frame_b = frames[1]

    piv = pypiv.DirectPIV(frame_a, frame_b, window_size=32,
                            search_size=32, distance=16)
    u, v = piv.correlate_frames()

    adapt_piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=16,
                                  ipmethod='cubic')
    u, v = adapt_piv.correlate_frames()

    adapt_piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=8,
                                  ipmethod='cubic')
    u, v = adapt_piv.correlate_frames()

    plt.imshow(u)
    plt.clim(-5, 5)
    plt.show() 
Example 14
Project: dave   Author: barentsen   File: test_fbls.py    MIT License 6 votes vote down vote up
def makePlots(time, flux, periods, blsArray, per, epc):
        mp.figure(1)
        mp.clf()
        mp.plot(time, flux, 'bo', mec="none")

        for i in range(17):
            mp.axvline(epc+np.min(time)+ i*per, color='r')

        mp.figure(2)
        mp.clf();
        bb = blsArray.max(axis=1)
        mp.imshow(bb, cmap=mp.cm.YlGnBu_r, interpolation="nearest", origin="bottom", aspect="auto")
#        mp.clim(vmin=0)
        mp.colorbar()

        mp.figure(3)
        mp.clf()
        bbb = bb.max(axis=1)
        mp.plot(periods, bbb, 'b-')
        mp.xlabel("Period") 
Example 15
Project: monsoon-onset   Author: jenfly   File: scratchpad.py    MIT License 6 votes vote down vote up
def animate(data, day, axlims=(-30, 45, 40, 120), dx=5, dy=5, climits=(-5, 15),
            cmap='BuPu', d0=138, clev=np.arange(5, 15.5, 1),
            cticks=np.arange(5, 16, 2.5)):
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v)
    plt.title(title)
    plt.draw()

# Need to scale arrows in quiver plot so that they are consistent across
# different days 
Example 16
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 17
Project: monsoon-onset   Author: jenfly   File: pub-figs-jclim.py    MIT License 6 votes vote down vote up
def mld_map(mld, m=None, month=5, cmap='hot_r', climits=(0, 70),
            cticks=range(0, 71, 10), clevs=None):
    cb_kwargs = {'ticks' : cticks, 'extend' : 'max'}
    if m is None:
        m = atm.init_latlon(0, 35, 58, 102, resolution='l', coastlines=False,
                            fillcontinents=True)
        m.drawcoastlines(linewidth=0.5, color='0.5')
    if min(climits) > 0 :
        cb_kwargs['extend'] = 'both'
    if clevs is None:
        # pcolormesh plot
        atm.pcolor_latlon(mld.sel(month=month), m=m, cmap=cmap,
                          cb_kwargs=cb_kwargs)
    else:
        # Contour plot
        atm.contourf_latlon(mld.sel(month=month), clev=clevs, m=m,
                            cmap=cmap, extend=cb_kwargs['extend'],
                            cb_kwargs=cb_kwargs)
    plt.clim(climits)
    return m 
Example 18
Project: PyGEM   Author: drounce   File: pygemfxns_output.py    MIT License 6 votes vote down vote up
def plot_latlonvar(lons, lats, variable, rangelow, rangehigh, title, xlabel, ylabel, colormap, east, west, south, north, 
                   xtick, ytick):
    """
    Plot a variable according to its latitude and longitude
    """
    # Create the projection
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    # Add country borders for reference
    ax.add_feature(cartopy.feature.BORDERS)
    # Set the extent
    ax.set_extent([east, west, south, north], cartopy.crs.PlateCarree())
    # Label title, x, and y axes
    plt.title(title)
    ax.set_xticks(np.arange(east,west+1,xtick), cartopy.crs.PlateCarree())
    ax.set_yticks(np.arange(south,north+1,ytick), cartopy.crs.PlateCarree())
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    # Plot the data 
    plt.scatter(lons, lats, c=variable, cmap=colormap)
    #  plotting x, y, size [s=__], color bar [c=__]
    plt.clim(rangelow,rangehigh)
    #  set the range of the color bar
    plt.colorbar(fraction=0.02, pad=0.04)
    #  fraction resizes the colorbar, pad is the space between the plot and colorbar
    plt.show() 
Example 19
Project: mom6-tools   Author: NCAR   File: surface_flux_analysis_MOM6_CESM.py    Apache License 2.0 6 votes vote down vote up
def make_plot(lon, lat, field, title, xmin=-280, xmax=80, ymin=-80, ymax=90, cmin=-200, cmax=200, xlabel=False):
   ''' Lat/Lon plot with anotations
   '''
   global area
   field_min = numpy.amin(field)
   field_max = numpy.amax(field)
   field_ave = (field*area).sum() / area.sum()
   ch = plt.pcolormesh(lon,lat,field)
   cbax=plt.colorbar(ch, extend='both')
   plt.title(r''+title)
   if (cmin != 0.0 or cmax != 0.0):
     plt.clim(cmin,cmax)

   plt.xlim(xmin,xmax)
   plt.ylim(ymin,ymax)
   plt.ylabel(r'Latitude [$\degree$N]')
   if xlabel: plt.xlabel(r'Longitude')
   axis = plt.gca()
   axis.annotate('max=%5.2f\nmin=%5.2f\nave=%5.2f'%(field_max,field_min,field_ave),xy=(0.01,0.73),
              xycoords='axes fraction', verticalalignment='bottom', fontsize=8, color='black')

   return 
Example 20
Project: AeroPy   Author: leal26   File: fitting.py    MIT License 5 votes vote down vote up
def plot_study(self, relative=True):
        if relative:
            z = self.rel_error
        else:
            z = self.error
        fig, ax = plt.subplots()
        cs = ax.contourf(self.P1, self.P2, z, np.linspace(0, 1, 101))

        fig.colorbar(cs, ticks=np.linspace(0, 1, 6))
        # plt.clim(0, 1)
        plt.xlabel(self.p1_name)
        plt.ylabel(self.p2_name)
        plt.show() 
Example 21
Project: dave   Author: barentsen   File: tesscentroid.py    MIT License 5 votes vote down vote up
def show():
    path = '/home/fergal/data/tess/hlsp_tess-data-alerts_tess_phot_00307210830-s02_tess_v1_tp.fits'
    fits, hdr = pyfits.getdata(path, header=True)

    cube = ktpf.getTargetPixelArrayFromFits(fits, hdr)

    for i in range(1000, 1002):
        plt.clf()
        mn = np.fabs(np.min(cube[i,:,:])) + 1
        plt.imshow(np.log10(cube[i,:,:]), origin="bottom")
#        plt.imshow(cube[i,:,:], origin="bottom", cmap=plt.cm.bone)
#        plt.clim(-20, 100)
        plt.colorbar()
        plt.title(i)
        plt.pause(1) 
Example 22
Project: dave   Author: barentsen   File: diffimg.py    MIT License 5 votes vote down vote up
def plotDiffDiagnostic(diff, oot):
    """Only works on my machine"""
    mp.subplot(121)
#    img = np.log10(1+diff - np.min(diff[np.isfinite(diff)]))
    plotTpf.plotCadence(diff, axis="relative")
    mp.colorbar()
    mp.subplot(122)
    plotTpf.plotCadence(diff/np.sqrt(2*oot), axis="relative")
    mp.colorbar()
    mp.clim(-3.0, 3.0) 
Example 23
Project: dave   Author: barentsen   File: play.py    MIT License 5 votes vote down vote up
def plotDiffer(cube, hdr, index):

    diff = cube[index]- cube[index+1]
    mp.clf()

    mp.subplot(221)
    plotTpf.plotCadence(cube[index], hdr)
    mp.colorbar()

    mp.subplot(222)
    plotTpf.plotCadence(cube[index+1], hdr)
    mp.colorbar()

    mp.subplot(223)
    plotTpf.plotCadence(diff, hdr)
    mp.colorbar()

    mp.subplot(224)
    noise = np.sqrt(cube[index]+cube[index+1])
    z = diff/noise
    plotTpf.plotCadence(z, hdr)

    idx = np.isfinite(z)
    zmax = max( -np.min(z[idx]), np.max(z[idx]))
    mp.clim([-zmax, zmax])
    mp.colorbar() 
Example 24
Project: monsoon-onset   Author: jenfly   File: scratchpad.py    MIT License 5 votes vote down vote up
def animate(data, day, axlims=(-30, 45, 40, 120), dx=5, dy=5, climits=(-5, 15),
            cmap='BuPu', d0=138, clev=np.arange(5, 15.5, 1),
            cticks=np.arange(5, 16, 2.5)):
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v)
    plt.title(title)
    plt.draw()

# Need to scale arrows in quiver plot so that they are consistent across
# different days 
Example 25
Project: monsoon-onset   Author: jenfly   File: thesis-figs.py    MIT License 5 votes vote down vote up
def mld_map(mld, cmap='Blues', axlims=(0, 35, 58, 102), climits=(10, 60),
            cticks=range(10, 71, 10), clevs=None):
    cb_kwargs = {'ticks' : cticks, 'extend' : 'both'}
    m = atm.init_latlon(axlims[0], axlims[1], axlims[2], axlims[3],
                        resolution='l', coastlines=False,
                        fillcontinents=True)
    m.drawcoastlines(linewidth=0.5, color='0.5')
    atm.pcolor_latlon(mld, m=m, cmap=cmap, cb_kwargs=cb_kwargs)
    plt.clim(climits) 
Example 26
Project: monsoon-onset   Author: jenfly   File: thesis-figs.py    MIT License 5 votes vote down vote up
def animate(i):
    days = range(-136, 227, 1)
    day = days[i]
    axlims=(-30, 45, 40, 120)
    dx, dy = 5, 5
    climits=(0, 20)
    cmap = 'hot_r'
    d0 = 138
    cticks=np.arange(4, 21, 2)
    scale = 250
    clev=np.arange(4, 20.5, 1)
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    yticks = range(-20, 41, 10)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.yticks(yticks, atm.latlon_labels(yticks, 'lat'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v, scale=scale, pivot='middle')
    plt.title(title)
    plt.draw() 
Example 27
Project: monsoon-onset   Author: jenfly   File: analyze-composites.py    MIT License 5 votes vote down vote up
def animate(i):
        plt.clf()
        m, _ = atm.pcolor_latlon(animdata[i], axlims=axlims, cmap=cmap)
        plt.clim(cmin, cmax)
        day = animdata[daynm + 'rel'].values[i]
        plt.title('%s %s RelDay %d' % (varnm, yearstr, day))
        return m 
Example 28
Project: monsoon-onset   Author: jenfly   File: regression-analysis.py    MIT License 5 votes vote down vote up
def sector_plot(var, p, stipple_kw={}, grp=None, ylim=None,
                yticks=None, clim=None):
    xname, yname = 'dayrel', 'lat'
    pts_mask = stipple_mask(p)
    lat = atm.get_coord(var, 'lat')
    days = atm.get_coord(var, 'dayrel')
    xsample = 3
    if max(np.diff(lat)) > 1:
        ysample = 1
    else:
        ysample = 2
    #utils.contourf_lat_time(lat, days, var)
    vals = np.ma.masked_array(var.T.values, mask=np.isnan(var.T))
    plt.pcolormesh(days, lat, vals, cmap='RdBu_r')
    cb = plt.colorbar()
    atm.stipple_pts(pts_mask, xname, yname, xsample, ysample, **stipple_kw)
    plt.title(varnm)
    plt.xlabel('Relative Day')
    plt.ylabel('Latitude')
    plt.grid(True)
    xticks = np.arange(-120, 201, 30)
    xlims = (-120, 200)
    plt.xlim(xlims)
    plt.xticks(xticks)
    if grp is not None:
        if grp.col > 0:
            plt.ylabel('')
        if grp.row < grp.nrow - 1:
            plt.xlabel('')
    if ylim is not None:
        plt.ylim(ylim)
    if yticks is not None:
        plt.yticks(yticks)
    if clim is not None:
        plt.clim(clim)
    else:
        clim = atm.climits(var, symmetric=True, percentile=99.9)
        plt.clim(clim) 
Example 29
Project: monsoon-onset   Author: jenfly   File: regression-analysis.py    MIT License 5 votes vote down vote up
def latlon_plot(varnm, reg, day_or_season, coeff='m', stipple_kw={},
                axlims=(-60, 60, 40, 120)):
    regdata = reg[varnm + '_latlon']
    keys = [key for key in regdata if key.endswith('_' + coeff)]
    clim = atm.climits(regdata[keys].to_array(), symmetric=True,
                        percentile=99.9)
    xname, yname = 'lon', 'lat'
    lat = atm.get_coord(regdata, 'lat')
    if max(np.diff(lat)) > 1:
        xsample, ysample = 1, 1
    else:
        xsample, ysample = 2, 2
    if isinstance(day_or_season, int):
        key = varnm + '_DAILY_'
        var = regdata[key + coeff].sel(dayrel=day_or_season)
        p = regdata[key + 'p'].sel(dayrel=day_or_season)
        titlestr = varnm + ' Day %d' % day_or_season
    else:
        key = varnm + '_' + day_or_season + '_'
        var = regdata[key + coeff]
        p = regdata[key + 'p']
        titlestr = varnm + ' ' + day_or_season
    pts_mask = stipple_mask(p)
    atm.pcolor_latlon(var, axlims=axlims, fancy=False)
    plt.clim(clim)
    atm.stipple_pts(pts_mask, xname, yname, xsample, ysample, **stipple_kw)
    plt.title(titlestr)


# Latitude-day contour plots of sector mean 
Example 30
Project: keras-training   Author: hls-fpga-machine-learning   File: eval.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_confusion_matrix(cm, classes,
                          normalize=False, 
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    #plt.title(title)
    cbar = plt.colorbar()
    plt.clim(0,1)
    cbar.set_label(title)
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    #plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
Example 31
Project: ERP-beamformer   Author: wmvanvliet   File: psychic_interface.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_spatial_pattern(spatial_pattern, fig=None):
    if fig is None:
        fig = plt.figure()

    cm = np.max(np.abs(spatial_pattern.data))
    psychic.scalpplot.plot_scalp(spatial_pattern.data.flatten(),
                                 spatial_pattern.ids[0, :],
                                 cmap=plt.get_cmap('RdBu_r'))
    plt.clim(-cm, cm)
    plt.title('spatial pattern')

    return fig 
Example 32
Project: KelvinHelmholtzInstability   Author: pmocz   File: KelvinHelmholtzInstability.py    MIT License 5 votes vote down vote up
def myPlot():
  plt.clf()
  plt.imshow(rho.T)
  plt.clim(0.8, 2.2)
  ax = plt.gca()
  ax.invert_yaxis()
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  plt.draw() 
Example 33
Project: CRFBiaffineParser   Author: wfxedu   File: network_crf.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 34
Project: CRFBiaffineParser   Author: wfxedu   File: network.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 35
Project: CRFBiaffineParser   Author: wfxedu   File: network_scores.py    Apache License 2.0 5 votes vote down vote up
def savefigs(self, sess, optimizer=False):
    """"""
    
    import gc
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    matdir = os.path.join(self.save_dir, 'matrices')
    if not os.path.isdir(matdir):
      os.mkdir(matdir)
    for var in self.save_vars:
      if optimizer or ('Optimizer' not in var.name):
        print(var.name)
        mat = sess.run(var)
        if len(mat.shape) == 1:
          mat = mat[None,:]
        plt.figure()
        try:
          plt.pcolor(mat, cmap='RdBu')
          plt.gca().invert_yaxis()
          plt.colorbar()
          plt.clim(vmin=-1, vmax=1)
          plt.title(var.name)
          plt.savefig(os.path.join(matdir, var.name.replace('/', '-')))
        except ValueError:
          pass
        plt.close()
        del mat
        gc.collect()
    
  #============================================================= 
Example 36
Project: PyGEM   Author: drounce   File: pygemfxns_postprocessing.py    MIT License 5 votes vote down vote up
def plot_latlonvar(lons, lats, variable, rangelow, rangehigh, title, xlabel, ylabel, colormap, east, west, south, north, 
                   xtick=1, 
                   ytick=1, 
                   marker_size=2,
                   option_savefig=0, 
                   fig_fn='Samplefig_fn.png',
                   output_filepath = input.main_directory + '/../Output/'):
    """
    Plot a variable according to its latitude and longitude
    """
    # Create the projection
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    # Add country borders for reference
    ax.add_feature(cartopy.feature.BORDERS)
    # Set the extent
    ax.set_extent([east, west, south, north], cartopy.crs.PlateCarree())
    # Label title, x, and y axes
    plt.title(title)
    ax.set_xticks(np.arange(east,west+1,xtick), cartopy.crs.PlateCarree())
    ax.set_yticks(np.arange(south,north+1,ytick), cartopy.crs.PlateCarree())
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    # Plot the data 
    plt.scatter(lons, lats, s=marker_size, c=variable, cmap='RdBu', marker='o', edgecolor='black', linewidths=0.25)
    #  plotting x, y, size [s=__], color bar [c=__]
    plt.clim(rangelow,rangehigh)
    #  set the range of the color bar
    plt.colorbar(fraction=0.02, pad=0.04)
    #  fraction resizes the colorbar, pad is the space between the plot and colorbar
    if option_savefig == 1:
        plt.savefig(output_filepath + fig_fn)
    plt.show() 
Example 37
Project: cloudnetpy   Author: tukiains   File: plotting.py    MIT License 5 votes vote down vote up
def plot_2d(data, cbar=True, cmap='viridis', ncolors=50, clim=None):
    """Simple plot of 2d variable."""
    plt.close()
    if cbar:
        cmap = plt.get_cmap(cmap, ncolors)
        plt.imshow(ma.masked_equal(data, 0).T, aspect='auto', origin='lower', cmap=cmap)
        plt.colorbar()
    else:
        plt.imshow(ma.masked_equal(data, 0).T, aspect='auto', origin='lower')
    if clim:
        plt.clim(clim)
    plt.show() 
Example 38
Project: fluctana   Author: minjunJchoi   File: fluctana.py    MIT License 5 votes vote down vote up
def spec(self, dnum=0, cnl=[0], nfft=512, **kwargs):
        if 'flimits' in kwargs: flimits = kwargs['flimits']*1000
        if 'xlimits' in kwargs: xlimits = kwargs['xlimits']

        fs = self.Dlist[dnum].fs
        nov = nfft*0.9

        for c in cnl:
            pshot = self.Dlist[dnum].shot
            pname = self.Dlist[dnum].clist[c]
            pbase = self.Dlist[dnum].time
            pdata = self.Dlist[dnum].data[c,:]

            pxx, freq, time, cax = plt.specgram(pdata, NFFT=nfft, Fs=fs, noverlap=nov,
                                                xextent=[pbase[0], pbase[-1]], cmap=CM)  # spectrum

            maxP = math.log(np.amax(pxx),10)*10
            minP = math.log(np.amin(pxx),10)*10
            dP = maxP - minP
            plt.clim([minP+dP*0.55, maxP])
            plt.colorbar(cax)

            if 'flimits' in kwargs:  # flimits
                plt.ylim([flimits[0], flimits[1]])
            if 'xlimits' in kwargs:  # xlimits
                plt.ylim([xlimits[0], xlimits[1]])
            else:
                plt.xlim([pbase[0], pbase[-1]])

            plt.title(pname, fontsize=10)  # labeling
            plt.xlabel('Time [s]')
            plt.ylabel('Frequency [Hz]')

            plt.show() 
Example 39
Project: segmentator   Author: ofgulban   File: gui_utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def updateColorBar(self, val):
        """Update slider for scaling log colorbar in 2D hist."""
        histVMax = np.power(10, self.sHistC.val)
        plt.clim(vmax=histVMax) 
Example 40
Project: atmos-tools   Author: jenfly   File: plots.py    MIT License 5 votes vote down vote up
def colorbar_symm(**kwargs):
    """Create a colorbar with limits symmetric about zero.

    Optional keyword arguments are inputs to plt.colorbar().
    """
    cb = plt.colorbar(**kwargs)
    cmax = abs(cb.boundaries).max()
    plt.clim(-cmax, cmax)


# ---------------------------------------------------------------------- 
Example 41
Project: monsoon-onset   Author: jenfly   File: pub-figs-jclim.py    MIT License 4 votes vote down vote up
def contourf_latday(var, clev=None, title='', cticks=None, climits=None,
                    nc_pref=40, grp=None,
                    xlims=(-120, 200), xticks=np.arange(-120, 201, 30),
                    ylims=(-60, 60), yticks=np.arange(-60, 61, 20),
                    dlist=None, grid=False, ind_nm='onset', xlabels=True):
    var = atm.subset(var, {'lat' : ylims})
    vals = var.values.T
    lat = atm.get_coord(var, 'lat')
    days = atm.get_coord(var, 'dayrel')
    cmap = get_colormap(var.name)
    if var.min() < 0:
        symmetric = True
    else:
        symmetric = False
    if var.name.startswith('PCP'):
        extend = 'max'
    else:
        extend = 'both'
    if clev == None:
        cint = atm.cinterval(vals, n_pref=nc_pref, symmetric=symmetric)
        clev = atm.clevels(vals, cint, symmetric=symmetric)
    elif len(atm.makelist(clev)) == 1:
        if var.name == 'PREC':
            clev = np.arange(0, 10 + clev/2.0, clev)
        else:
            clev = atm.clevels(vals, clev, symmetric=symmetric)

    plt.contourf(days, lat, vals, clev, cmap=cmap, extend=extend)
    plt.colorbar(ticks=cticks)
    plt.clim(climits)
    atm.ax_lims_ticks(xlims, xticks, ylims, yticks)
    plt.grid(grid)
    #plt.title(title)
    if dlist is not None:
        for d0 in dlist:
            plt.axvline(d0, color='k')
    if xlabels:
        plt.gca().set_xticklabels(xticks)
        plt.xlabel('Days Since ' + ind_nm.capitalize())
    else:
        plt.gca().set_xticklabels([])
    if grp is not None and grp.col == 0:
        plt.ylabel('Latitude') 
Example 42
Project: sklearn_pydata2015   Author: jakevdp   File: figures.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def visualize_tree(estimator, X, y, boundaries=True,
                   xlim=None, ylim=None):
    estimator.fit(X, y)

    if xlim is None:
        xlim = (X[:, 0].min() - 0.1, X[:, 0].max() + 0.1)
    if ylim is None:
        ylim = (X[:, 1].min() - 0.1, X[:, 1].max() + 0.1)

    x_min, x_max = xlim
    y_min, y_max = ylim
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
                         np.linspace(y_min, y_max, 100))
    Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, alpha=0.2, cmap='rainbow')
    plt.clim(y.min(), y.max())

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='rainbow')
    plt.axis('off')

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)        
    plt.clim(y.min(), y.max())
    
    # Plot the decision boundaries
    def plot_boundaries(i, xlim, ylim):
        if i < 0:
            return

        tree = estimator.tree_
        
        if tree.feature[i] == 0:
            plt.plot([tree.threshold[i], tree.threshold[i]], ylim, '-k')
            plot_boundaries(tree.children_left[i],
                            [xlim[0], tree.threshold[i]], ylim)
            plot_boundaries(tree.children_right[i],
                            [tree.threshold[i], xlim[1]], ylim)
        
        elif tree.feature[i] == 1:
            plt.plot(xlim, [tree.threshold[i], tree.threshold[i]], '-k')
            plot_boundaries(tree.children_left[i], xlim,
                            [ylim[0], tree.threshold[i]])
            plot_boundaries(tree.children_right[i], xlim,
                            [tree.threshold[i], ylim[1]])
            
    if boundaries:
        plot_boundaries(0, plt.xlim(), plt.ylim()) 
Example 43
Project: MachineLearning   Author: LocalGroupAstrostatistics2015   File: figures.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def visualize_tree(estimator, X, y, boundaries=True,
                   xlim=None, ylim=None):
    estimator.fit(X, y)

    if xlim is None:
        xlim = (X[:, 0].min() - 0.1, X[:, 0].max() + 0.1)
    if ylim is None:
        ylim = (X[:, 1].min() - 0.1, X[:, 1].max() + 0.1)

    x_min, x_max = xlim
    y_min, y_max = ylim
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
                         np.linspace(y_min, y_max, 100))
    Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, alpha=0.2, cmap='rainbow')
    plt.clim(y.min(), y.max())

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='rainbow')
    plt.axis('off')

    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)        
    plt.clim(y.min(), y.max())
    
    # Plot the decision boundaries
    def plot_boundaries(i, xlim, ylim):
        if i < 0:
            return

        tree = estimator.tree_
        
        if tree.feature[i] == 0:
            plt.plot([tree.threshold[i], tree.threshold[i]], ylim, '-k')
            plot_boundaries(tree.children_left[i],
                            [xlim[0], tree.threshold[i]], ylim)
            plot_boundaries(tree.children_right[i],
                            [tree.threshold[i], xlim[1]], ylim)
        
        elif tree.feature[i] == 1:
            plt.plot(xlim, [tree.threshold[i], tree.threshold[i]], '-k')
            plot_boundaries(tree.children_left[i], xlim,
                            [ylim[0], tree.threshold[i]])
            plot_boundaries(tree.children_right[i], xlim,
                            [tree.threshold[i], ylim[1]])
            
    if boundaries:
        plot_boundaries(0, plt.xlim(), plt.ylim()) 
Example 44
Project: pyPCGA   Author: jonghyunharrylee   File: tough.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_SAVE(self, dat, df, nx, y=0, col = 'Temperature', clim = [0, 100], figname=None):
        ''' plot_SAVE
        '''
        elevation_save = np.zeros((3000,1))
        for idblock in range(1,3001):
            elevation_save[idblock-1] = dat.grid.blocklist[idblock].centre[2]
            
        z = np.reshape(elevation_save,(nx[2],nx[1],nx[0]))
        
        data_save=np.array(df[col])
        
        if col == 'Pressure':
            # Gas pressure converted to m H2O + elevation = hydraulic head in water
            a = np.reshape(data_save*0.00010197,(nx[2],nx[1],nx[0])).T + z.T
            #a = np.reshape(data_save,(nx[2],nx[1],nx[0])).T 
            plt.imshow(a[:,y,:].T)
            #plt.colorbar()
            plt.clim(clim[0],clim[1])
            #plt.title('Hydraulic head (m)')
            plt.title('Pressure in Pa')
            plt.xlabel('x(m)')
            plt.ylabel('z(m)')
            plt.colorbar(orientation='horizontal')
            
        elif col == 'Temperature':
            a = np.reshape(data_save,(nx[2],nx[1],nx[0])).T
            plt.imshow(a[:,y,:].T)
            #plt.colorbar()
            plt.clim(clim[0],clim[1])
            plt.title('Temperature in C')
            plt.xlabel('x(m)')
            plt.ylabel('z(m)')
            plt.colorbar(orientation='horizontal')            
        elif col == 'Gas Pressure':
            raise NotImplementedError
        else:
            raise ValueError('it support (Gas )Pressure or Temperature')
        
        if figname is not None:
            plt.savefig(figname+'.png')    
        
        plt.close()

        return