当前位置: 首页>>代码示例>>Python>>正文


Python ColorbarBase.set_label方法代码示例

本文整理汇总了Python中matplotlib.colorbar.ColorbarBase.set_label方法的典型用法代码示例。如果您正苦于以下问题:Python ColorbarBase.set_label方法的具体用法?Python ColorbarBase.set_label怎么用?Python ColorbarBase.set_label使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.colorbar.ColorbarBase的用法示例。


在下文中一共展示了ColorbarBase.set_label方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: error_plot

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
    def error_plot(self, ax_lb, ax_ub, cax, cborientation='vertical'):
        # plot the error map
        ttP_lb = np.zeros((self.dims[1::]))
        ttP_ub = ttP_lb.copy()
        for _i1 in xrange(self.dims[1]):
            for _i2 in xrange(self.dims[2]):
                for _i3 in xrange(self.dims[3]):
                    ttP_lb[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 16)
                    ttP_ub[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 84)

        mlb = copy(self.m)
        mlb.ax = ax_lb
        mub = copy(self.m)
        mub.ax = ax_ub

        cmap = cm.get_cmap(self.cmapname)
        cmap.set_over('grey')

        mlb.contourf(self.x, self.y, ttP_lb[:, :, 0], cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mub.contourf(self.x, self.y, ttP_ub[:, :, 0], cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mlb.drawcoastlines(zorder=2)
        mlb.drawcountries(linewidth=1.0, zorder=2)
        mub.drawcoastlines(zorder=2)
        mub.drawcountries(linewidth=1.0, zorder=2)
        cb = ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=self.vmin,
                                                         vmax=self.vmax),
                         orientation=cborientation, extend=self.extend)
        cb.set_label(self.cb_label)
        return mlb, mub
开发者ID:FMassin,项目名称:SRL_2015,代码行数:37,代码来源:alerttimemap.py

示例2: MakeReflectColorbar

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def MakeReflectColorbar(ax=None, colorbarLabel="Reflectivity [dBZ]", **kwargs):
    # Probably need a smarter way to allow fine-grained control of properties
    # like fontsize and such...
    if ax is None:
        ax = plt.gca()

    cbar = ColorbarBase(ax, cmap=NWS_Reflect["ref_table"], norm=NWS_Reflect["norm"], **kwargs)
    cbar.set_label(colorbarLabel)
    return cbar
开发者ID:BVRoot,项目名称:BRadar,代码行数:11,代码来源:plotutils.py

示例3: scale

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def scale(args):
    dataset_name = args.get('dataset')
    scale = args.get('scale')
    scale = [float(component) for component in scale.split(',')]

    variable = args.get('variable')
    if variable.endswith('_anom'):
        variable = variable[0:-5]
        anom = True
    else:
        anom = False

    variable = variable.split(',')

    with open_dataset(get_dataset_url(dataset_name)) as dataset:
        variable_unit = get_variable_unit(dataset_name,
                                          dataset.variables[variable[0]])
        variable_name = get_variable_name(dataset_name,
                                          dataset.variables[variable[0]])

    if variable_unit.startswith("Kelvin"):
        variable_unit = "Celsius"

    if anom:
        cmap = colormap.colormaps['anomaly']
        variable_name = gettext("%s Anomaly") % variable_name
    else:
        cmap = colormap.find_colormap(variable_name)

    if len(variable) == 2:
        if not anom:
            cmap = colormap.colormaps.get('speed')

        variable_name = re.sub(
            r"(?i)( x | y |zonal |meridional |northward |eastward )", " ",
            variable_name)
        variable_name = re.sub(r" +", " ", variable_name)

    fig = plt.figure(figsize=(2, 5), dpi=75)
    ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
    norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])

    formatter = ScalarFormatter()
    formatter.set_powerlimits((-3, 4))
    bar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical',
                       format=formatter)
    bar.set_label("%s (%s)" % (variable_name.title(),
                               utils.mathtext(variable_unit)))

    buf = StringIO()
    try:
        plt.savefig(buf, format='png', dpi='figure', transparent=False,
                    bbox_inches='tight', pad_inches=0.05)
        plt.close(fig)
        return buf.getvalue()
    finally:
        buf.close()
开发者ID:michaelsmit,项目名称:ocean-navigator,代码行数:59,代码来源:tile.py

示例4: create_colorbar

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def create_colorbar(cmap, norm, title=None):
    # Make a figure and axes with dimensions as desired.
    fig = Figure(figsize=(4,0.2))
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_axes([0.005, 0.1, 0.985, 0.85])

    cb = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal', format=NullFormatter(), ticks=NullLocator() )
    if title:
        cb.set_label(title, fontsize=12)
    fig.savefig('/home/dotcloud/data/media/plot/colorbar.png', format='png', transparent=True)
开发者ID:fanez,项目名称:geostats,代码行数:12,代码来源:colorbar.py

示例5: plot

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def plot(countries,values,label='',clim=None,verbose=False):
    """
    Usage: worldmap.plot(countries, values [, label] [, clim])
    """
    countries_shp = shpreader.natural_earth(resolution='110m',category='cultural',
                                            name='admin_0_countries')
    ## Create a plot
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ## Create a colormap
    cmap = plt.get_cmap('RdYlGn_r')
    if clim:
       vmin = clim[0]
       vmax = clim[1]
    else:
       val = values[np.isfinite(values)]
       mean = val.mean()
       std = val.std()
       vmin = mean-2*std
       vmax = mean+2*std
    norm = Normalize(vmin=vmin,vmax=vmax)
    smap = ScalarMappable(norm=norm,cmap=cmap)
    ax2 = fig.add_axes([0.3, 0.18, 0.4, 0.03])
    cbar = ColorbarBase(ax2,cmap=cmap,norm=norm,orientation='horizontal')
    cbar.set_label(label)
    ## Add countries to the map
    for country in shpreader.Reader(countries_shp).records():
        countrycode = country.attributes['adm0_a3']
        countryname = country.attributes['name_long']
        ## Check for country code consistency
        if countrycode == 'SDS': #South Sudan
           countrycode = 'SSD'
        elif countrycode == 'ROU': #Romania
           countrycode = 'ROM'
        elif countrycode == 'COD': #Dem. Rep. Congo
           countrycode = 'ZAR'
        elif countrycode == 'KOS': #Kosovo
           countrycode = 'KSV'
        if countrycode in countries:
           val = values[countries==countrycode]
           if np.isfinite(val):
              color = smap.to_rgba(val)
           else:
              color = 'grey'
        else:
           color = 'w'
           if verbose:
              print("No data available for "+countrycode+": "+countryname)
        ax.add_geometries(country.geometry,ccrs.PlateCarree(),facecolor=color,label=countryname)
    plt.show()
开发者ID:andflopezbec,项目名称:Python,代码行数:52,代码来源:worldmap.py

示例6: get_colorbar

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
 def get_colorbar(self,title,label,min,max):
     '''Create a colorbar from given data.  Returns a png image as a string.'''
     
     fig=pylab.figure(figsize=(2,5))
     ax=fig.add_axes([0.35,0.03,0.1,0.9])
     norm=self.get_norm(min,max)
     formatter=self.get_formatter()
     if formatter:
         cb1 = ColorbarBase(ax,norm=norm,format=formatter,spacing='proportional',orientation='vertical')
     else:
         cb1 = ColorbarBase(ax,norm=norm,spacing='proportional',orientation='vertical')
     cb1.set_label(label,color='1')
     ax.set_title(title,color='1')
     for tl in ax.get_yticklabels():
         tl.set_color('1')
     im=cStringIO.StringIO()
     fig.savefig(im,dpi=300,format='png',transparent=True)
     pylab.close(fig)
     s=im.getvalue()
     im.close()
     return s
开发者ID:andrewsoong,项目名称:WRF-GoogleEarth,代码行数:23,代码来源:ncEarth.py

示例7: show_colormap

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def show_colormap(base):
    """Display a colormap.

    **Argument:**

    *base*
        The name of a base colormap or a `ColormapBase` instance to plot.

    """
    import matplotlib.pyplot as plt
    from matplotlib.colorbar import ColorbarBase
    try:
        base = get_colormap_base(base)
    except ValueError:
        pass
    cmap = create_colormap(base.ncolors, base=base.name)
    fig = plt.figure(figsize=(9, .7))
    ax = fig.add_axes([.01, .35, .98, .63])
    cb = ColorbarBase(ax, cmap=cmap, orientation='horizontal', ticks=[])
    cb.set_label('{:s}: {:d} colors'.format(base.name, base.ncolors))
    plt.show()
开发者ID:ajdawson,项目名称:colormaps,代码行数:23,代码来源:colormaps.py

示例8: make_plot_3d

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def make_plot_3d(grid, grid_name, x, y, all_z, t, grid_t_idx, grid_x_idx, grid_z_idx, n_cols = 6,
                 outpath='', filename_prefix='LMA',do_save=True, 
                 image_type='pdf', colormap='cubehelix' , grid_range=None): 

    n_frames = t.shape[0]
    # n_cols = 6
    n_rows = int(ceil( float(n_frames) / n_cols ))
  
    if type(colormap) == type(''):
        colormap = get_cmap(colormap)
    grey_color = (0.5,)*3
    frame_color = (0.2,)*3
    
    density_maxes = []
    total_counts = []
    all_t = []
   
    xedge = centers_to_edges(x)
    x_range = xedge.max() - xedge.min()
    yedge = centers_to_edges(y)
    y_range = yedge.max() - yedge.min()
    dx = (xedge[1]-xedge[0])

    # count_scale_factor = dx # / 1000.0
    # max_count_baseline = 450 * count_scale_factor #/ 10.0
    min_count, max_count = 1, grid[:].max() #max_count_baseline*(t[1]-t[0])
    if (max_count == 0) | (max_count == 1 ):
        max_count = min_count+1

    default_vmin = -0.2
    if np.log10(max_count) <= default_vmin:
        vmin_count = np.log10(max_count) + default_vmin
    else:
        vmin_count = default_vmin

    # If the range of values for the colorbar is manually specified, 
    # overwrite what we did above
    if grid_range is not None:
        vmin_count = grid_range[0]
        max_count = grid_range[1]
            
    # w, h = figaspect(float(n_rows)/n_cols) # breaks for large numbers of frames - has a hard-coded max figure size
    w, h, n_rows_perpage, n_pages = multiples_figaspect(n_rows, n_cols, x_range, y_range, fig_width=8.5, max_height=None)
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    p = small_multiples_plot(fig=fig, rows=n_rows, columns=n_cols)
    p.label_edges(True)
    pad = 0.0 # for time labels in each frame

    for ax in p.multiples.flat:
        ax.set_axis_bgcolor('white')
        ax.spines['top'].set_edgecolor(frame_color)
        ax.spines['bottom'].set_edgecolor(frame_color)
        ax.spines['left'].set_edgecolor(frame_color)
        ax.spines['right'].set_edgecolor(frame_color)
    #   ax.yaxis.set_major_formatter(kilo_formatter)
    #   ax.xaxis.set_major_formatter(kilo_formatter)
    base_date = datetime.strptime(t.units, "seconds since %Y-%m-%d %H:%M:%S")
    time_delta = timedelta(0,float(t[0]),0)
    start_time = base_date + time_delta
    for zi in range(len(all_z)):
        indexer = [slice(None),]*len(grid.shape)
                                
        frame_start_times = []
          
        altitude = all_z[zi]
        for i in range(n_frames):
            p.multiples.flat[i].clear()   # reset (clear) the axes
            frame_start = base_date + timedelta(0,float(t[i]),0)
            frame_start_times.append(frame_start)
            indexer[grid_t_idx] = i
            indexer[grid_z_idx] = zi
            density = grid[indexer]
            density = np.ma.masked_where(density<=0.0, density) # mask grids 0 grids to reveal background color
             
            # density,edges = np.histogramdd((x,y), bins=(xedge,yedge))
            density_plot  = p.multiples.flat[i].pcolormesh(xedge,yedge,
                                       np.log10(density.transpose()),
                                       vmin=vmin_count,
                                       vmax=np.log10(max_count),
                                       cmap=colormap)
            label_string = frame_start.strftime('%H%M:%S')
            x_lab = xedge[0]-pad+x_range*.015
            y_lab = yedge[0]-pad+y_range*.015
            text_label = p.multiples.flat[i].text(x_lab, y_lab, label_string, color=grey_color, size=6)
            density_plot.set_rasterized(True)
            density_maxes.append(density.max())
            total_counts.append(density.sum())
            all_t.append(frame_start)
            print(label_string, x_lab, y_lab, grid_name, density.max(), density.sum())

        color_scale = ColorbarBase(p.colorbar_ax, cmap=density_plot.cmap,
                                           norm=density_plot.norm,
                                           orientation='horizontal')

        # color_scale.set_label('count per pixel')
        color_scale.set_label('log10(count per pixel)')

        view_x = (xedge.min(), xedge.max())
#.........这里部分代码省略.........
开发者ID:Vsalinas91,项目名称:lmatools,代码行数:103,代码来源:multiples_nc.py

示例9: ColorbarBase

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
#!/usr/bin/env python
from BRadar.plotutils import NWS_Reflect


'''
Make a colorbar as a separate figure.
'''

#from matplotlib import pyplot, mpl
import matplotlib.pyplot as plt
from matplotlib.colorbar import ColorbarBase

# Make a figure and axes with dimensions as desired.
fig = plt.figure()
ax1 = fig.add_axes([0.45, 0.05, 0.03, 0.75])


# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar.  There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
cb1 = ColorbarBase(ax1, cmap=NWS_Reflect['ref_table'],
                                   norm=NWS_Reflect['norm'])
cb1.set_label('Reflectivity [dBZ]')

#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.eps')
#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.png', dpi=250)

plt.show()
开发者ID:BVRoot,项目名称:RadarClustering,代码行数:32,代码来源:RadarColorbar.py

示例10: m

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
# Plot candidate directions.
lvals = [src.l for src in cands.values()]
bvals = [src.b for src in cands.values()]
x, y = m(lvals, bvals)
cand_pts = m.scatter(x, y, marker='+', linewidths=.5, 
    edgecolors='k', facecolors='none', zorder=10)  # hi zorder -> top

# Plot tissots showing possible scale of candidate scatter.
for l, b in zip(lvals, bvals):
    m.tissot(l, b, 5., 30, ec='none', color='g', alpha=0.25)

# Show the closest candidate to each CR.
for cr in CRs.values():
    cand = cands[cr.near_id]
    m.geodesic(cr.l, cr.b, cand.l, cand.b, lw=0.5, ls='-', c='g')

plt.title('UHE Cosmic Rays and Candidate Sources')
plt.legend([cr_pts, cand_pts], ['UHE CR', 'Candidate'],
    frameon=False, loc='lower right', scatterpoints=1)

# Plot a colorbar for the CR energies.
cb_ax = plt.axes([0.25, .1, .5, .03], frameon=False)  # rect=L,B,W,H
#bar = ColorbarBase(cb_ax, cmap=cmap, orientation='horizontal', drawedges=False)
vals = np.linspace(Evals.min(), Evals.max(), 100)
bar = ColorbarBase(cb_ax, values=vals, norm=norm_E, cmap=cmap, 
    orientation='horizontal', drawedges=False)
bar.set_label('CR Energy (EeV)')

plt.show()
开发者ID:AvlWx2014,项目名称:basemap,代码行数:31,代码来源:allskymap_cr_example.py

示例11: Plotter

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
class Plotter():
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.average = settings.average
        self.axes = None
        self.bar = None
        self.threadPlot = None
        self.extent = None
        self.lineMinP = None
        self.lineMaxP = None
        self.lineAvgP = None
        self.lineGMP = None
        self.lineHalfP = None
        self.lineHalfFS = None
        self.lineHalfFE = None
        self.lineObwP = None
        self.lineObwFS = None
        self.lineObwFE = None

        self.labelMinP = None
        self.labelMaxP = None
        self.labelAvgP = None
        self.labelGMP = None
        self.labelHalfP = None
        self.labelHalfFS = None
        self.labelHalfFE = None
        self.labelObwFS = None
        self.labelObwFE = None

        self.setup_plot()
        self.set_grid(self.settings.grid)

    def setup_plot(self):
        formatter = ScalarFormatter(useOffset=False)

        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])

        self.axes = self.figure.add_subplot(gs[0],
                                            axisbg=self.settings.background)
        self.axes.set_xlabel("Frequency (MHz)")
        self.axes.set_ylabel('Level (dB)')
        self.axes.xaxis.set_major_formatter(formatter)
        self.axes.yaxis.set_major_formatter(formatter)
        self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.set_xlim(self.settings.start, self.settings.stop)
        self.axes.set_ylim(-50, 0)

        self.bar = self.figure.add_subplot(gs[1])
        norm = Normalize(vmin=-50, vmax=0)
        self.barBase = ColorbarBase(self.bar, norm=norm,
                                    cmap=cm.get_cmap(self.settings.colourMap))
        self.barBase.set_label('Level (dB)')

        self.setup_measure()

    def setup_measure(self):
        dashesAvg = [4, 5, 1, 5, 1, 5]
        dashesGM = [5, 5, 5, 5, 1, 5, 1, 5]
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lineMinP = Line2D([0, 0], [0, 0], linestyle='--', color='black')
        self.lineMaxP = Line2D([0, 0], [0, 0], linestyle='-.', color='black')
        self.lineAvgP = Line2D([0, 0], [0, 0], dashes=dashesAvg, color='magenta')
        self.lineGMP = Line2D([0, 0], [0, 0], dashes=dashesGM, color='green')
        self.lineHalfP = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineObwP = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        if matplotlib.__version__ >= '1.3':
            effect = patheffects.withStroke(linewidth=3, foreground="w",
                                            alpha=0.75)
            self.lineMinP.set_path_effects([effect])
            self.lineMaxP.set_path_effects([effect])
            self.lineAvgP.set_path_effects([effect])
            self.lineGMP.set_path_effects([effect])
            self.lineHalfP.set_path_effects([effect])
            self.lineHalfFS.set_path_effects([effect])
            self.lineHalfFE.set_path_effects([effect])
            self.lineObwP.set_path_effects([effect])
            self.lineObwFS.set_path_effects([effect])
            self.lineObwFE.set_path_effects([effect])

        self.axes.add_line(self.lineMinP)
        self.axes.add_line(self.lineMaxP)
        self.axes.add_line(self.lineAvgP)
        self.axes.add_line(self.lineGMP)
        self.axes.add_line(self.lineHalfP)
        self.axes.add_line(self.lineHalfFS)
        self.axes.add_line(self.lineHalfFE)
        self.axes.add_line(self.lineObwP)
        self.axes.add_line(self.lineObwFS)
        self.axes.add_line(self.lineObwFE)

        box = dict(boxstyle='round', fc='white', ec='black')
        self.labelMinP = Text(0, 0, 'Min', fontsize='x-small', ha="right",
                              va="bottom", bbox=box, color='black')
#.........这里部分代码省略.........
开发者ID:vlslv,项目名称:RTLSDR-Scanner,代码行数:103,代码来源:plot.py

示例12: ppi_plot

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
        ppi_plot(init_data.xlocs, init_data.ylocs, init_data.vel_h_ts, norm=vel_norm, cmap=cmap, ax=ax4, rings=rings)
        ax4.set_title('TS Velocity (m/s)')

        ax6 = fig.add_subplot(nrow, ncol, 6, sharex=ax, sharey=ax)
        ppi_plot(init_data.xlocs, init_data.ylocs, init_data.spw_h_ts, norm=spw_norm, cmap=cmap, ax=ax6, rings=rings)
        ax6.set_title('TS Spectrum Width (m/s)')

    fig.subplots_adjust(bottom=0.15)
    lpos = list(ax.get_position().bounds)
    lpos[1] = 0.04
    lpos[3] = 0.04
    cax_left = fig.add_axes(lpos)

    cbar_left = ColorbarBase(ax=cax_left,
        norm=pwr_norm, cmap=cmap, orientation='horizontal')
    cbar_left.set_label('Power (dBm)')

    mpos = list(ax3.get_position().bounds)
    mpos[1] = 0.04
    mpos[3] = 0.04
    cax_mid = fig.add_axes(mpos)
    cbar_mid = ColorbarBase(ax=cax_mid,
        norm=vel_norm, cmap=cmap, orientation='horizontal')
    cbar_mid.set_label('Velocity (m/s)')

    rpos = list(ax5.get_position().bounds)
    rpos[1] = 0.04
    rpos[3] = 0.04
    cax_right = fig.add_axes(rpos)
    cbar_right = ColorbarBase(ax=cax_right,
        norm=spw_norm, cmap=cmap, orientation='horizontal')
开发者ID:dopplershift,项目名称:DissertationCode,代码行数:33,代码来源:plot_data.py

示例13: __init__

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
class Spectrogram:
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.data = [[], [], []]
        self.index = 0
        self.axes = None
        self.plot = None
        self.extent = None
        self.lineHalfFS = None
        self.lineHalfFE = None
        self.lineObwFS = None
        self.lineObwFE = None

        self.labelHalfFS = None
        self.labelHalfFE = None
        self.labelObwFS = None
        self.labelObwFE = None

        self.threadPlot = None
        self.setup_plot()
        self.set_grid(self.settings.grid)

    def setup_plot(self):
        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
        self.axes = self.figure.add_subplot(gs[0],
                                            axisbg=self.settings.background)

        self.axes.set_xlabel("Frequency (MHz)")
        self.axes.set_ylabel('Time')
        numFormatter = ScalarFormatter(useOffset=False)
        timeFormatter = DateFormatter("%H:%M:%S")

        self.axes.xaxis.set_major_formatter(numFormatter)
        self.axes.yaxis.set_major_formatter(timeFormatter)
        self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.set_xlim(self.settings.start, self.settings.stop)
        now = time.time()
        self.axes.set_ylim(epoch_to_mpl(now), epoch_to_mpl(now - 10))

        self.bar = self.figure.add_subplot(gs[1])
        norm = Normalize(vmin=-50, vmax=0)
        self.barBase = ColorbarBase(self.bar, norm=norm,
                                    cmap=cm.get_cmap(self.settings.colourMap))
        self.barBase.set_label('Level (dB)')

        self.setup_measure()

    def setup_measure(self):
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lineHalfFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineObwFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        if matplotlib.__version__ >= '1.3':
            effect = patheffects.withStroke(linewidth=3, foreground="w",
                                            alpha=0.75)
            self.lineHalfFS.set_path_effects([effect])
            self.lineHalfFE.set_path_effects([effect])
            self.lineObwFS.set_path_effects([effect])
            self.lineObwFE.set_path_effects([effect])

        self.axes.add_line(self.lineHalfFS)
        self.axes.add_line(self.lineHalfFE)
        self.axes.add_line(self.lineObwFS)
        self.axes.add_line(self.lineObwFE)

        box = dict(boxstyle='round', fc='white', ec='purple')
        self.labelHalfFS = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        self.labelHalfFE = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        box['ec'] = '#996600'
        self.labelObwFS = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')
        self.labelObwFE = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')

        self.axes.add_artist(self.labelHalfFS)
        self.axes.add_artist(self.labelHalfFE)
        self.axes.add_artist(self.labelObwFS)
        self.axes.add_artist(self.labelObwFE)

        self.hide_measure()

    def draw_vline(self, line, label, x):
        yLim = self.axes.get_ylim()
        xLim = self.axes.get_xlim()
        if xLim[0] < x < xLim[1]:
            line.set_visible(True)
            line.set_xdata([x, x])
            line.set_ydata([yLim[0], yLim[1]])
            self.axes.draw_artist(line)
            label.set_visible(True)
            label.set_position((x, yLim[1]))
            self.axes.draw_artist(label)

    def draw_measure(self, background, measure, show):
#.........这里部分代码省略.........
开发者ID:vlslv,项目名称:RTLSDR-Scanner,代码行数:103,代码来源:spectrogram.py

示例14: statistics

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]

#.........这里部分代码省略.........
        dataY = []
        popup_values = []

        fig = plt.figure()
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
        m = self.background_map(ax)
        cmap = cm.ScalarMappable(norm=Normalize(vmin=0, vmax=2), cmap='RdBu_r')
        stats_used = []
        for lon, lat, dep, delay, evid, lat1, lon1, dmag, time, mag, rfn in \
            zip(lons, lats, deps, diff, pid, lats1, lons1, magdiff, ot, mags, rfns):
            allcnt += 1
            try:
                if eventinfo is not None and len(eventinfo[evid]) != 4:
                    # print "Event %s does not have 4 initial picks." % evid
                    continue
            except KeyError:
                print "No event information available for: %s (%s)" % (evid, UTCDateTime(time))
                continue
            if evid in self.event_excludes:
                print "Event %s was set to be excluded." % evid
                continue

            if computedelay:
                # Compute the expected alert time for the actual epicenter and
                # the first stations that detected the event
                class NetworkInfo:
                    def __init__(self):
                        self.networks = {'ca':{'lat': [], 'lon': [], 'chn': [],
                                               'nw': [], 'nm': [], 'lc': [],
                                               'color':'black',
                                               'label':'UC Berkeley'}}
                    def get_networks(self):
                        return self.networks

                # read in SCEDC master station list
                fh = open(stationfn)
                scedc_stations = {}
                for _l in fh.readlines():
                    if _l.startswith('#'):
                        continue
                    net, sta, chan, loc, lt, ln, elev, ondate, offdate = _l.split()
                    ns = '.'.join((net, sta))
                    if ns not in scedc_stations:
                        scedc_stations[ns] = (float(lt), float(ln))
                ni = NetworkInfo()
                for _st in eventinfo[evid]:
                    ni.networks['ca']['lat'].append(scedc_stations[_st][0])
                    ni.networks['ca']['lon'].append(scedc_stations[_st][1])
                    ni.networks['ca']['nm'].append(_st)
                    if _st not in stats_used:
                        stats_used.append(_st)
                de = DelayEEW()
                elat, elon, edep, ttP, tstarget = \
                de.compute(ni, np.array([float(lon)]), np.array([float(lat)]),
                           np.array([float(dep)]),
                           vp=6.5, vs=3.5, nnst=4, procdelay=True, nmaps=500,
                           resultsfn=None, latencies=latencies)
                med = np.median(ttP)
                lb = scoreatpercentile(ttP, perc_min)
                ub = scoreatpercentile(ttP, perc_max)
            else:
                distance, index = tree.query(np.array([[lat, lon]]))
                irow, icol = divmod(index[0], lats_tt.shape[1])
                med = np.median(times[:, irow, icol])
                lb = scoreatpercentile(times[:, irow, icol], perc_min)
                ub = scoreatpercentile(times[:, irow, icol], perc_max)

            cnt += 1
            allm.append(mag)
            val = (delay - lb) / (ub - lb)
            print med, lb, ub, delay, val, med - delay
            vals.append(val)
            cl = cmap.to_rgba(val)
            x, y = m(lon, lat)
            dataX.append(x)
            dataY.append(y)
            info = '%s: %.2f %s\n' % (UTCDateTime(time), mag, evid)
            info += '%.2f %.2f %.2f\n' % (delay, med, val)
            for _st in eventinfo[evid]:
                info += ' %s' % _st
            popup_values.append(info)
            m.plot(x, y, ms=8, c=cl, marker='o', picker=5.)
            # plt.figure()
            # plt.hist(times[ilon, ilat, :], bins=np.arange(0, 30), normed=True, histtype='step')
            # plt.show()
        print "Stations used in detections:"
        print stats_used
        idx = np.where((np.array(vals) <= 1.0) & (np.array(vals) >= 0))
        print "%.1f lie within the %d and %d percentile" % ((idx[0].size / float(len(vals))) * 100, perc_min, perc_max)
        # plt.plot(allm, vals, 'bo')
        if interactive:
            self.popup(fig, dataX, dataY, popup_values)
        cax = fig.add_axes([0.87, 0.1, 0.05, 0.8])
        cb = ColorbarBase(cax, cmap='RdBu_r',
                          norm=Normalize(vmin=0, vmax=2))
        cb.set_label('Alert accuracy')

        plt.figure()
        plt.hist(vals, bins=20)
        plt.show()
开发者ID:FMassin,项目名称:SRL_2015,代码行数:104,代码来源:eewvs_alert_times.py

示例15: create_multipanel_plot

# 需要导入模块: from matplotlib.colorbar import ColorbarBase [as 别名]
# 或者: from matplotlib.colorbar.ColorbarBase import set_label [as 别名]
def create_multipanel_plot(size, dpi, shape, layout, var_info, cmap, lims):
        fig = plt.figure(figsize=size, dpi=dpi)
        rings = []

        # the rect parameter will be ignore as we will set axes_locator
        rect = (0.08, 0.08, 0.9, 0.9)
        nrow,ncol = shape

        # divide the axes rectangle into grid whose size is specified
        # by horiz * vert
        horiz = [Scaled(1.)]
        for i in range(ncol - 1):
            horiz.extend([Fixed(.2), Scaled(1.)])

        vert = [Scaled(.1), Fixed(.35), Scaled(1.)]
        for i in range(nrow - 1):
            vert.extend([Fixed(.1), Scaled(1.)])

        divider = Divider(fig, rect, horiz, vert, aspect=False)

#        ax0 = fig.add_axes(rect, label="0")
#        ax0.set_aspect('equal', 'datalim')
#        ax = [ax0] + [fig.add_axes(rect, label="%d"%i, sharex=ax0, sharey=ax0)
#            for i in range(1,6)]
        ax = [fig.add_axes(rect, label="%d"%i) for i in range(len(layout))]
        cax = [fig.add_axes(rect, label='cb%d'%i) for i in range(ncol)]

        for i,a in enumerate(ax):
#            a.set_axes_locator(divider.new_locator(nx=(i // nrow) * 2,
#                ny=((i%nrow) + 1) * 2))
            a.set_axes_locator(divider.new_locator(nx=(i % ncol) * 2,
                ny=(nrow - (i // ncol)) * 2))
            a.set_aspect('equal', 'datalim')

        for i,a in enumerate(cax):
            a.set_axes_locator(divider.new_locator(nx=2 * i, ny=0))

        for num,(a,(data, label, var)) in enumerate(zip(ax, layout)):
            norm,ticks,units = var_info[var]
            ppi_plot(init_data.xlocs, init_data.ylocs, data, norm=norm,
                cmap=cmap, ax=a, rings=rings)
#            a.set_title('%s (%s)' % (moment, units))

            if num >= ncol:
                a.set_xlabel('X Distance (km)')
                cbar = ColorbarBase(ax=cax[num%ncol], norm=norm, cmap=cmap,
                    orientation='horizontal')
                cbar.set_label('%s (%s)' % (label, units))
                cbar.set_ticks(ticks)
            else:
                a.xaxis.set_major_formatter(plt.NullFormatter())

            if num % ncol == 0:
                a.set_ylabel('Y Distance (km)')
            else:
                a.yaxis.set_major_formatter(plt.NullFormatter())

            if lims:
                a.xaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.yaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.set_xlim(*lims[1:3])
                a.set_ylim(*lims[3:])

            # loc = 2 is upper left. TODO: Should patch matplotlib to use
            # same strings as legend
            at = AnchoredText("%s)" % chr(97 + num), loc=2, prop=dict(size='large'),
                frameon=True)
#            at.patch.set_boxstyle("round, pad=0., rounding_size=0.2")
            a.add_artist(at)

        return fig
开发者ID:dopplershift,项目名称:DissertationCode,代码行数:73,代码来源:make_ppis.py


注:本文中的matplotlib.colorbar.ColorbarBase.set_label方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。