本文整理汇总了Python中matplotlib.pyplot.colorbar函数的典型用法代码示例。如果您正苦于以下问题:Python colorbar函数的具体用法?Python colorbar怎么用?Python colorbar使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了colorbar函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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()
示例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
示例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)
示例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
示例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')
示例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)")
示例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
示例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
示例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)
示例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')
示例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')
示例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()
示例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)
示例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)