本文整理汇总了Python中matplotlib.pyplot.colorbar函数的典型用法代码示例。如果您正苦于以下问题:Python colorbar函数的具体用法?Python colorbar怎么用?Python colorbar使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了colorbar函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __call__
def __call__(self,iteration):
p = self.t.calcPress(iteration,pOnly=True)
plt.imshow(p[:,0,:],origin=0)
plt.axis('tight')
plt.colorbar()
开发者ID:BenByington,项目名称:PythonTools,代码行数:7,代码来源:calc_series.py
示例2: plotmapdBtime
def plotmapdBtime():
pcolormesh(yoko, time*1e6, dB(S11c), vmin=-65, vmax=-30)
title("Reflection (dB) vs flux \n and time (1 us pulse) at 4.46 GHz")
xlabel("Flux (V)")
ylabel("Time (us)")
#ylim(0, 1.5)
colorbar()
开发者ID:priyanka27s,项目名称:TA_software,代码行数:7,代码来源:D1006_refl_time_domain.py
示例3: test_minimized_rasterized
def test_minimized_rasterized():
# This ensures that the rasterized content in the colorbars is
# only as thick as the colorbar, and doesn't extend to other parts
# of the image. See #5814. While the original bug exists only
# in Postscript, the best way to detect it is to generate SVG
# and then parse the output to make sure the two colorbar images
# are the same size.
from xml.etree import ElementTree
np.random.seed(0)
data = np.random.rand(10, 10)
fig, ax = plt.subplots(1, 2)
p1 = ax[0].pcolormesh(data)
p2 = ax[1].pcolormesh(data)
plt.colorbar(p1, ax=ax[0])
plt.colorbar(p2, ax=ax[1])
buff = io.BytesIO()
plt.savefig(buff, format='svg')
buff = io.BytesIO(buff.getvalue())
tree = ElementTree.parse(buff)
width = None
for image in tree.iter('image'):
if width is None:
width = image['width']
else:
if image['width'] != width:
assert False
开发者ID:4over7,项目名称:matplotlib,代码行数:31,代码来源:test_image.py
示例4: implot
def implot(plt, x, y, Z, ax=None, colorbar=True, **kwargs):
"""Image plot of general data (like imshow but with non-pixel axes).
Parameters
----------
plt : plot object
Plot object, typically `matplotlib.pyplot`.
x : (M,) array_like
Vector of x-axis points, must be linear (equally spaced).
y : (N,) array_like
Vector of y-axis points, must be linear (equally spaced).
Z : (M, N) array_like
Matrix of data to be displayed, the value at each (x, y) point.
ax : axis object (optional)
A specific axis to plot on (defaults to `plt.gca()`).
colorbar: boolean (optional)
Whether to plot a colorbar.
**kwargs
Additional arguments for `ax.imshow`.
"""
ax = plt.gca() if ax is None else ax
def is_linear(x):
diff = np.diff(x)
return np.allclose(diff, diff[0])
assert is_linear(x) and is_linear(y)
image = ax.imshow(Z, aspect='auto', extent=(x[0], x[-1], y[-1], y[0]),
**kwargs)
if colorbar:
plt.colorbar(image, ax=ax)
开发者ID:Ocode,项目名称:nengo,代码行数:31,代码来源:matplotlib.py
示例5: plot_jacobian
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6):
"""
Customized visualization of jacobian matrices for observing
sparsity patterns
"""
plt.figure()
fig, ax = plt.subplots()
if normalize is True:
plt.imshow(A, interpolation='none', cmap=cmap,
norm = mpl.colors.Normalize(vmin=-1.,vmax=1.))
else:
plt.imshow(A, interpolation='none', cmap=cmap)
plt.colorbar(format=ticker.FuncFormatter(fmt))
ax.spy(A, marker='.', markersize=0, precision=precision)
ax.spines['right'].set_visible(True)
ax.spines['bottom'].set_visible(True)
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('left')
xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int)
ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int)
plt.xticks(xlabels)
plt.yticks(ylabels)
plt.savefig(name, bbox_inches='tight', pad_inches=0.05)
plt.close()
return
开发者ID:komahanb,项目名称:pchaos,代码行数:35,代码来源:plotter.py
示例6: plot_confusion_matrix
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`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
开发者ID:KenAhon,项目名称:own_data_cnn_implementation_keras,代码行数:32,代码来源:updated_custom_data_cnn.py
示例7: streamlineBxz_dens
def streamlineBxz_dens():
fig=plt.figure()
ppy=yt.ProjectionPlot(ds, "y", "Bxz", weight_field="density") #Project X-component of B-field from z-direction
By=ppy._frb["density"]
ax=fig.add_subplot(111)
plt.xticks(tick_locs,tick_lbls)
plt.yticks(tick_locs,tick_lbls)
Bymag=ax.pcolormesh(np.log10(By), cmap="YlGn")
cbar_m=plt.colorbar(Bymag)
cbar_m.set_label("density")
res=800
#densxy=Density2D(0,1) #integrated density along given axis
U=Flattenx(0,1) #X-magnetic field integrated along given axis
V=Flattenz(0,1) #Z-magnetic field
#U=np.asarray(zip(*x2)[::-1]) #rotate the matrix 90 degrees to correct orientation to match projected plots
#V=np.asarray(zip(*y2)[::-1])
norm=np.sqrt(U**2+V**2) #magnitude of the vector
Unorm=U/norm #normalise vectors
Vnorm=V/norm
#mask_Unorm=np.ma.masked_where(densxy<np.mean(densxy),Unorm) #create a masked array of Unorm values only in high density regions
#mask_Vnorm=np.ma.masked_where(densxy<np.mean(densxy),Vnorm)
X,Y=np.meshgrid(np.linspace(0,res,64, endpoint=True),np.linspace(0,res,64,endpoint=True))
streams=plt.streamplot(X,Y,Unorm,Vnorm,color=norm*1e6,density=(3,3),cmap=plt.cm.autumn)
cbar=plt.colorbar(orientation="horizontal")
cbar.set_label('Bxz streamlines (uG)')
plt.title("Bxz streamlines on weighted density projection")
plt.xlabel("(1e4 AU)")
plt.ylabel("(1e4 AU)")
开发者ID:jwyl,项目名称:joycesoft,代码行数:29,代码来源:testfunctions.py
示例8: plot_heat_net
def plot_heat_net(net_mat, sectors):
"""Plot a heat map of the net relations.
Parameters
----------
net_mat: np.ndarray
the net represented in a matrix way.
sectors: list
the name of the elements of the adjacency matrix network.
Returns
-------
fig: matplotlib.pyplot.figure
the figure of the matrix heatmap.
"""
vmax = np.sort([np.abs(net_mat.max()), np.abs(net_mat.min())])[::-1][0]
n_sectors = len(sectors)
assert(net_mat.shape[0] == net_mat.shape[1])
assert(n_sectors == len(net_mat))
fig = plt.figure()
plt.imshow(net_mat, interpolation='none', cmap=plt.cm.RdYlGn,
vmin=-vmax, vmax=vmax)
plt.xticks(range(n_sectors), sectors)
plt.yticks(range(n_sectors), sectors)
plt.xticks(rotation=90)
plt.colorbar()
return fig
开发者ID:tgquintela,项目名称:pythonUtils,代码行数:29,代码来源:net_plotting.py
示例9: test_unimodality_of_GEV
def test_unimodality_of_GEV(self):
x0 = 1500
mu = 1000
data = np.array([x0])
ksi = np.arange(-2, 2, 0.01)
sigma = np.arange(10, 8000, 10)
n_ksi = len(ksi)
n_sigma = len(sigma)
z = np.zeros((n_ksi, n_sigma))
for i, the_ksi in enumerate(ksi):
for j, the_sigma in enumerate(sigma):
z[i, j] = gevfit.objective_function_stationary_high([the_sigma, mu, the_ksi], data)
sigma, ksi = np.meshgrid(sigma, ksi)
z = np.ma.masked_where(z == gevfit.BIG_NUM, z)
z = np.ma.masked_where(z > 9, z)
plt.figure()
plt.pcolormesh(ksi, sigma, z)
plt.colorbar()
plt.xlabel('$\\xi$')
plt.ylabel('$\\sigma$')
plt.title('$\\mu = %.1f, x = %.1f$' % (mu, x0))
plt.show()
pass
开发者ID:guziy,项目名称:GevFit,代码行数:34,代码来源:test_gevfit.py
示例10: corrplot
def corrplot(C, cmap=None, cmap_range=(0.,1.), cbar=True, fontsize=14, **kwargs):
"""
Plots values in a correlation matrix
"""
ax = kwargs['ax']
n = len(C)
# defaults
if cmap is None:
if min(cmap_range) >= 0:
cmap = "OrRd"
elif max(cmap_range) <= 0:
cmap = "RdBu"
else:
cmap = "gray"
# remove values
rr, cc = np.triu_indices(n, k=1)
C[rr, cc] = np.nan
vmin, vmax = cmap_range
img = ax.imshow(C, cmap=cmap, vmin=vmin, vmax=vmax, aspect='equal')
if cbar:
plt.colorbar(img) #, shrink=0.75)
for j in range(n):
for i in range(j+1,n):
ax.text(i, j, '{:0.2f}'.format(C[i,j]), fontsize=fontsize,
fontdict={'ha': 'center', 'va': 'center'})
noticks(ax=ax)
开发者ID:lmcintosh,项目名称:jetpack,代码行数:34,代码来源:chart.py
示例11: plot_confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=None,
zmin=1):
"""This function prints and plots the confusion matrix for the intent classification.
Normalization can be applied by setting `normalize=True`."""
import numpy as np
zmax = cm.max()
plt.imshow(cm, interpolation='nearest', cmap=cmap if cmap else plt.cm.Blues, aspect='auto',
norm=LogNorm(vmin=zmin, vmax=zmax))
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
logger.info("Normalized confusion matrix: \n{}".format(cm))
else:
logger.info("Confusion matrix, without normalization: \n{}".format(cm))
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
开发者ID:DominicBreuker,项目名称:rasa_nlu,代码行数:33,代码来源:evaluate.py
示例12: plot_map
def plot_map(AX, fname, mmin=0,mmax=1, annot='A', xoff=False,yoff=False, xlab='None', ylab='None', aspect=False, row_lab=None, col_lab=None, log=False):
global xtix, ytix, xtix_loc, ytix_loc, fsa, fs
mmap = np.genfromtxt(fname, delimiter=',')
if log:
mmap = np.log(mmap)
im = AX.pcolor(mmap, vmin=mmin, vmax=mmax)
plt.colorbar(im, ax=AX)
AX.annotate(annot, (0,0), (0.02,0.9), color='white', fontsize= fsa, fontweight='bold', xycoords='data', textcoords='axes fraction')
if row_lab != None:
AX.annotate(row_lab, xy=(0.0, 0.5), size='x-large', ha='right', va='center', xytext= (-4.5, 5))#(-ax.yaxis.labelpad - pad, 0),xycoords=ax.yaxis.label, textcoords='offset points'
if col_lab != None:
AX.set_title(col_lab)
AX.set_xticks(xtix_loc)
AX.set_yticks(ytix_loc)
if xoff:
AX.set_xticklabels('')
else:
AX.set_xticklabels(xtix)
if yoff:
AX.set_yticklabels('')
else:
AX.set_yticklabels(ytix)
if xlab != 'None':
AX.set_xlabel(xlab, fontsize = fs)
if ylab != 'None':
AX.set_ylabel(ylab, fontsize = fs)
if aspect:
AX.set_aspect('equal', 'datalim')
开发者ID:rustyBilges,项目名称:chapter5_clean_analysis,代码行数:33,代码来源:plot_heatmap3.py
示例13: get_heatmap
def get_heatmap(data_mat, name_for_saving_files, pp,stimulus_on_time, stimulus_off_time,delta_ff, f0_start, f0_end):
#Plot heatmap for validation
A1 = np.reshape(data_mat, (np.size(data_mat,0)*np.size(data_mat,1), np.size(data_mat,2)))
if delta_ff == 1:
delta_ff_A1 = np.zeros(np.shape(A1))
for ii in xrange(0,np.size(A1,0)):
delta_ff_A1[ii,:] = (A1[ii,:]-np.mean(A1[ii,f0_start:f0_end]))/(np.std(A1[ii,f0_start:f0_end])+0.1)
B = np.argsort(np.mean(delta_ff_A1, axis=1))
print np.max(delta_ff_A1)
else:
B = np.argsort(np.mean(A1, axis=1))
print np.max(A1)
with sns.axes_style("white"):
C = A1[B,:][-2000:,:]
fig2 = plt.imshow(C,aspect='auto', cmap='jet', vmin = np.min(C), vmax = np.max(C))
plot_vertical_lines_onset(stimulus_on_time)
plot_vertical_lines_offset(stimulus_off_time)
plt.title(name_for_saving_files)
plt.colorbar()
fig2 = plt.gcf()
pp.savefig(fig2)
plt.close()
开发者ID:seethakris,项目名称:Charlie_Data,代码行数:26,代码来源:create_heatmaps.py
示例14: plotTimeseries
def plotTimeseries(mytimes,myyears,times,mydata,myvar,depthlevels,mytype):
depthlevels=-np.asarray(depthlevels)
ax = figure().add_subplot(111)
y,x = np.meshgrid(depthlevels,times)
mydata=np.rot90(mydata)
if myvar=='temp':
levels = np.arange(-2,16,1)
if myvar=='salt':
levels = np.arange(mydata.min(),mydata.max()+0.1,0.05)
if mytype=="T-CLASS3-IC_CHANGE":
levels = np.arange(mydata.min(),mydata.max()+0.1,0.1)
if mytype=="S-CLASS3-IC_CHANGE":
levels = np.arange(mydata.min(),mydata.max()+0.1,0.05)
print mydata.min(), mydata.max()
cs=contourf(x,y,mydata,levels,cmap=cm.get_cmap('RdBu_r',len(levels)-1))
plt.colorbar(cs)
xticks(mytimes,myyears,rotation=-90)
plotfile='figures/'+str(mytype)+'_'+str(myvar)+'_alldepths.pdf'
plt.savefig(plotfile,dpi=300)
print 'Saved figure file %s\n'%(plotfile)
开发者ID:trondkr,项目名称:romstools,代码行数:25,代码来源:createHoevmoeller.py
示例15: lasso_regression
def lasso_regression(features, solutions, verbose=0):
columns = solutions.columns
clf = Lasso(alpha=1e-4, max_iter=5000)
print('Training Model... ')
clf.fit(features, solutions)
feature_coeff = clf.coef_
features_importances = np.zeros((169, 3))
for idx in range(3):
features_importance = np.reshape(feature_coeff[idx, :], (169, 8))
features_importance = np.max(features_importance, axis=1)
features_importances[:, idx] = features_importance
features_importance_max = np.max(features_importances, axis=1)
features_importance_max = np.reshape(features_importance_max, (13, 13))
plt.pcolor(features_importance_max)
plt.title("Feature importance for HoG")
plt.colorbar()
plt.xticks(arange(0.5,13.5), range(1, 14))
plt.yticks(arange(0.5,13.5), range(1, 14))
plt.axis([0, 13, 0, 13])
plt.show()
print('Done Training')
return (clf, columns)
开发者ID:jkcn90,项目名称:kaggle_galaxy_zoo,代码行数:27,代码来源:models.py
示例16: _erfimage_imshow
def _erfimage_imshow(ax, ch_idx, tmin, tmax, vmin, vmax, ylim=None,
data=None, epochs=None, sigma=None,
order=None, scalings=None, vline=None,
x_label=None, y_label=None, colorbar=False,
cmap='RdBu_r'):
"""Aux function to plot erfimage on sensor topography"""
from scipy import ndimage
import matplotlib.pyplot as plt
this_data = data[:, ch_idx, :].copy()
ch_type = channel_type(epochs.info, ch_idx)
if ch_type not in scalings:
raise KeyError('%s channel type not in scalings' % ch_type)
this_data *= scalings[ch_type]
if callable(order):
order = order(epochs.times, this_data)
if order is not None:
this_data = this_data[order]
if sigma > 0.:
this_data = ndimage.gaussian_filter1d(this_data, sigma=sigma, axis=0)
ax.imshow(this_data, extent=[tmin, tmax, 0, len(data)], aspect='auto',
origin='lower', vmin=vmin, vmax=vmax, picker=True,
cmap=cmap, interpolation='nearest')
if x_label is not None:
plt.xlabel(x_label)
if y_label is not None:
plt.ylabel(y_label)
if colorbar:
plt.colorbar()
开发者ID:leggitta,项目名称:mne-python,代码行数:33,代码来源:topo.py
示例17: TuningResponseArea
def TuningResponseArea(tuningCurves, unitKey='', figPath=[]):
""" Plot the tuning response area for tuning curve data.
:param tuningCurves: pandas.DataFrame from spreadsheet with experimental data loaded from Excel file
:type tuningCurves: pandas.core.DataFrame
:param unitKey: identifying string for data, possibly unit name/number and test number
:type unitKey: str
:param figPath: Directory location for plots to be saved
:type figPath: str
"""
f = plt.figure()
colorRange = (-10,10.1)
I = np.unique(np.array(tuningCurves['intensity']))
F = np.array(tuningCurves['freq'])
R = np.array(np.zeros((len(I), len(F))))
for ci, i in enumerate(I):
for cf, f in enumerate(F):
R[ci,cf] = tuningCurves['response'].where(tuningCurves['intensity']==i).where(tuningCurves['freq']==f).dropna().values[0]
levelRange = np.arange(colorRange[0], colorRange[1], (colorRange[1]-colorRange[0])/float(25*(colorRange[1]-colorRange[0])))
sns.set_context(rc={"figure.figsize": (7, 4)})
ax = plt.contourf(F, I, R)#, vmin=colorRange[0], vmax=colorRange[1], levels=levelRange, cmap = cm.bwr )
plt.colorbar()
# plt.title(unit, fontsize=14)
plt.xlabel('Frequency (kHz)', fontsize=14)
plt.ylabel('Intensity (dB)', fontsize=14)
if len(figPath)>0:
plt.savefig(figPath + 'tuningArea_' + unitKey +'.png')
开发者ID:pdroberts,项目名称:StimResponse,代码行数:26,代码来源:PharmaFunctions.py
示例18: demo_locatable_axes_hard
def demo_locatable_axes_hard(fig1):
from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size
divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)
# axes for image
ax = LocatableAxes(fig1, divider.get_position())
# axes for colorbar
ax_cb = LocatableAxes(fig1, divider.get_position())
h = [Size.AxesX(ax), Size.Fixed(0.05), Size.Fixed(0.2)] # main axes # padding, 0.1 inch # colorbar, 0.3 inch
v = [Size.AxesY(ax)]
divider.set_horizontal(h)
divider.set_vertical(v)
ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))
fig1.add_axes(ax)
fig1.add_axes(ax_cb)
ax_cb.axis["left"].toggle(all=False)
ax_cb.axis["right"].toggle(ticks=True)
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent, interpolation="nearest")
plt.colorbar(im, cax=ax_cb)
plt.setp(ax_cb.get_yticklabels(), visible=False)
开发者ID:KevKeating,项目名称:matplotlib,代码行数:33,代码来源:demo_axes_divider.py
示例19: run
def run(meth = 'moment'):
out,srts = bs.run0(arr = arr, itr = 2, meth = meth)
f = myplots.fignum(3,(12,6))
ax = f.add_subplot(111)
csrts = [s for s in srts if len(s) == len(cols)][0]
rsrts = [s for s in srts if len(s) == len(rows)][0]
cprint = [rows[rs] for rs in rsrts]
rprint = [cols[cs] for cs in csrts]
im = ax.imshow(out,
interpolation= 'nearest',
cmap = plt.get_cmap('OrRd'),
)
#flip the rows and columns... looks better.
ax.set_xticks(arange(len(cols))+.25)
ax.set_yticks(arange(len(rows))+.25)
ax.set_yticklabels([e for e in cprint])
ax.set_xticklabels(rprint)
print 'rows: \n{0}'.format(', '.join([e.strip() for e in rprint]))
print
print 'cols: \n{0}'.format(', '.join([e.strip() for e in cprint]))
plt.colorbar(im)
f.savefig(myplots.figpath('correlation_plot_2_4_{0}.pdf')
.format(meth))
return
开发者ID:bh0085,项目名称:compbio,代码行数:32,代码来源:corrs_2_4_2012.py
示例20: el_plot
def el_plot(data, Map=False, show=True):
"""
Plot the elevation for the region from the last time series
:Parameters:
**data** -- the standard python data dictionary
**Map** -- {True, False} (optional): Optional argument. If True,
the elevation will be plotted on a map.
"""
trigrid = data['trigrid']
plt.gca().set_aspect('equal')
plt.tripcolor(trigrid, data['zeta'][-1,:])
plt.colorbar()
plt.title("Elevation")
if Map:
#we set the corners of where the map should show up
llcrnrlon, urcrnrlon = plt.xlim()
llcrnrlat, urcrnrlat = plt.ylim()
#we construct the map. Note that resolution serves to increase
#or decrease the detail in the coastline. Currently set to
#'i' for 'intermediate'
m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
resolution='i', suppress_ticks=False)
#set color for continents. Default is grey.
m.fillcontinents(color='ForestGreen')
m.drawmapboundary()
m.drawcoastlines()
if show:
plt.show()
开发者ID:RobieH,项目名称:Karsten-datatools,代码行数:30,代码来源:plottools.py
注:本文中的matplotlib.pyplot.colorbar函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论