本文整理汇总了Python中matplotlib.colorbar.ColorbarBase类的典型用法代码示例。如果您正苦于以下问题:Python ColorbarBase类的具体用法?Python ColorbarBase怎么用?Python ColorbarBase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ColorbarBase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error_plot
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
示例2: scale
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()
示例3: MakeReflectColorbar
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
示例4: create_colorbar
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)
示例5: spikesplot_cb
def spikesplot_cb(position, cmap='viridis', fig=None):
# Add colorbar
if fig is None:
fig = plt.gcf()
cax = fig.add_axes(position)
cb = ColorbarBase(cax, cmap=get_cmap(cmap), spacing='proportional',
orientation='horizontal', drawedges=False)
cb.set_ticks([0, 0.5, 1.0])
cb.set_ticklabels(['Inferior', '(axial slice)', 'Superior'])
cb.outline.set_linewidth(0)
cb.ax.xaxis.set_tick_params(width=0)
return cax
示例6: plot
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()
示例7: __setup_plot
def __setup_plot(self):
gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
self.axes = self.figure.add_subplot(gs[0], projection='3d')
numformatter = ScalarFormatter(useOffset=False)
timeFormatter = DateFormatter("%H:%M:%S")
self.axes.set_xlabel("Frequency (MHz)")
self.axes.set_ylabel('Time')
self.axes.set_zlabel('Level ($\mathsf{dB/\sqrt{Hz}}$)')
colour = hex2color(self.settings.background)
colour += (1,)
self.axes.w_xaxis.set_pane_color(colour)
self.axes.w_yaxis.set_pane_color(colour)
self.axes.w_zaxis.set_pane_color(colour)
self.axes.xaxis.set_major_formatter(numformatter)
self.axes.yaxis.set_major_formatter(timeFormatter)
self.axes.zaxis.set_major_formatter(numformatter)
self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
self.axes.zaxis.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.axes.set_zlim(-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))
示例8: __setup_plot
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(utc_to_mpl(now), utc_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.__setup_measure()
self.__setup_overflow()
self.hide_measure()
示例9: draw_colorbar
def draw_colorbar(self,im,vmin,vmax):
""" draw colorbar """
if self.cb:
self.fig.delaxes(self.fig.axes[1])
self.fig.subplots_adjust(right=0.90)
pos = self.axes.get_position()
l, b, w, h = pos.bounds
cax = self.fig.add_axes([l, b-0.06, w, 0.03]) # colorbar axes
cmap=self.cMap(self.varName)
substName = self.varName
if not self.cMap.ticks_label.has_key(self.varName):
# we couldn't find 'vel_f', so try searching for 'vel'
u = self.varName.find('_')
if u:
substName = self.varName[:u]
if not self.cMap.ticks_label.has_key(substName):
msgBox = gui.QMessageBox()
msgBox.setText(
""" Please define a color scale for '{0}' in your configuration file """.format(self.varName))
msgBox.exec_()
raise RuntimeError(
""" Please define a color scale for '{0}' in your configuration file """.format(self.varName))
bounds = self.cMap.ticks_label[substName]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
self.cb = ColorbarBase(cax, cmap=cmap, norm=norm, orientation='horizontal', boundaries=bounds,ticks=bounds)#, format='%1i') ## spacing='proportional' -- divide proportionally by the value
self.cb.ax.tick_params(labelsize=8)
#t = [str(int(i)) for i in bounds]
t = [str(i) for i in bounds]
self.cb.set_ticklabels(t,update_ticks=True)
self.cb.set_label('Color Scale', size=8)
示例10: get_colorbar
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
示例11: __init__
def __init__(self, parent, colourMap):
wx.Panel.__init__(self, parent)
dpi = wx.ScreenDC().GetPPI()[0]
figure = matplotlib.figure.Figure(facecolor='white', dpi=dpi)
figure.set_size_inches(200.0 / dpi, 25.0 / dpi)
self.canvas = FigureCanvas(self, -1, figure)
axes = figure.add_subplot(111)
figure.subplots_adjust(0, 0, 1, 1)
norm = Normalize(vmin=0, vmax=1)
self.bar = ColorbarBase(axes, norm=norm, orientation='horizontal',
cmap=cm.get_cmap(colourMap))
axes.xaxis.set_visible(False)
示例12: show_colormap
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()
示例13: _colorbar_show
def _colorbar_show(self, im, threshold):
if threshold is None:
offset = 0
else:
offset = threshold
if offset > im.norm.vmax:
offset = im.norm.vmax
# create new axis for the colorbar
figure = self.frame_axes.figure
_, y0, x1, y1 = self.rect
height = y1 - y0
x_adjusted_width = self._colorbar_width / len(self.axes)
x_adjusted_margin = self._colorbar_margin['right'] / len(self.axes)
lt_wid_top_ht = [x1 - (x_adjusted_width + x_adjusted_margin),
y0 + self._colorbar_margin['top'],
x_adjusted_width,
height - (self._colorbar_margin['top'] +
self._colorbar_margin['bottom'])]
self._colorbar_ax = figure.add_axes(lt_wid_top_ht, axis_bgcolor='w')
our_cmap = im.cmap
# edge case where the data has a single value
# yields a cryptic matplotlib error message
# when trying to plot the color bar
nb_ticks = 5 if im.norm.vmin != im.norm.vmax else 1
ticks = np.linspace(im.norm.vmin, im.norm.vmax, nb_ticks)
bounds = np.linspace(im.norm.vmin, im.norm.vmax, our_cmap.N)
# some colormap hacking
cmaplist = [our_cmap(i) for i in range(our_cmap.N)]
istart = int(im.norm(-offset, clip=True) * (our_cmap.N - 1))
istop = int(im.norm(offset, clip=True) * (our_cmap.N - 1))
for i in range(istart, istop):
cmaplist[i] = (0.5, 0.5, 0.5, 1.) # just an average gray color
if im.norm.vmin == im.norm.vmax: # len(np.unique(data)) == 1 ?
return
else:
our_cmap = our_cmap.from_list('Custom cmap', cmaplist, our_cmap.N)
self._cbar = ColorbarBase(
self._colorbar_ax, ticks=ticks, norm=im.norm,
orientation='vertical', cmap=our_cmap, boundaries=bounds,
spacing='proportional')
self._cbar.set_ticklabels(["%.2g" % t for t in ticks])
self._colorbar_ax.yaxis.tick_left()
tick_color = 'w' if self._black_bg else 'k'
for tick in self._colorbar_ax.yaxis.get_ticklabels():
tick.set_color(tick_color)
self._colorbar_ax.yaxis.set_tick_params(width=0)
self._cbar.update_ticks()
示例14: pic_switch
def pic_switch(event):
bounds = roi1.export()
if zoom.value_selected == 'Zoom':
axpic.cla()
axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected)
axpic.set_title(start.file_list[int(pic_swap.val)])
axpic.set_xlim(bounds[2], bounds[3])
axpic.set_ylim(bounds[1], bounds[0])
axpic.axvline(x=bounds[2])
axpic.axvline(x=bounds[3])
axpic.axhline(y=bounds[0])
axpic.axhline(y=bounds[1])
axbar.cla()
norm = Normalize(vmin=vmin.val, vmax=vmax.val)
col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal')
col.set_ticks([vmin.val, vmax.val], update_ticks=True)
else:
axpic.cla()
axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected)
axpic.set_title(start.file_list[int(pic_swap.val)])
axpic.axvline(x=bounds[2])
axpic.axvline(x=bounds[3])
axpic.axhline(y=bounds[0])
axpic.axhline(y=bounds[1])
axbar.cla()
norm = Normalize(vmin=vmin.val, vmax=vmax.val)
col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal')
col.set_ticks([vmin.val, vmax.val], update_ticks=True)
示例15: display_median_price_animation
def display_median_price_animation(self):
"""Kicks off the animation of median price information."""
fig = plotter.figure(num = 1, figsize = (10, 12), tight_layout = True)
fig.canvas.set_window_title('Percent increase in median house ' + \
'price since 1996')
axis = fig.add_axes([0.85, 0.04, 0.03, 0.92])
colorbar_ticks = [0, .2, .4, .6, .8, 1.0]
colorbar_labels = ['-100%', '0%', '250%', '500%', '750%', '>1000%']
colorbar = ColorbarBase(axis, self._colormap, orientation='vertical')
colorbar.set_ticks(colorbar_ticks)
colorbar.set_ticklabels(colorbar_labels)
fig.add_axes([0.0, 0.0, 0.82, 1.0])
anim = FuncAnimation(fig,
self._animate,
frames = self.endyear + 1 - self.startyear,
interval = 1000,
blit = True,
init_func = self._init_animate,
repeat_delay = 3000)
plotter.show()