本文整理汇总了Python中matplotlib.pyplot.get_cmap函数的典型用法代码示例。如果您正苦于以下问题:Python get_cmap函数的具体用法?Python get_cmap怎么用?Python get_cmap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_cmap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show_grid
def show_grid(grid, start, person, maxdiv):
fig = plt.figure(3)
vmin = None#np.min(grid)
vmax = None#np.max(grid)/maxdiv
cmap_name = 'inferno'
print(grid.shape, vmin, vmax)
for i in range(grid.shape[1]):
print(i, np.sum(grid[:,i,:]))
for i in range(9):
a = fig.add_subplot(2,5,i+1)
plt.imshow(grid[:,start+i,:], cmap=plt.get_cmap(cmap_name), vmin=vmin, vmax=vmax, interpolation='nearest')
a.set_title(str(start+i))
fig = plt.figure(30)
a = fig.add_subplot(1,1,1)
tmp = np.sum(grid[:,person,:], axis=1)/np.max(grid)
vmin = np.min(tmp)
vmax = np.max(tmp)/maxdiv
print(vmin, vmax)
plt.imshow(tmp, cmap=plt.get_cmap(cmap_name), vmin=vmin, vmax=vmax, interpolation='nearest')
a.set_title('cost')
示例2: plot_color_gradients
def plot_color_gradients(cmap_category, cmap_list):
nrows = len(cmap_list)
fig, axes = plt.subplots(nrows=nrows, ncols=2)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.05)
fig.suptitle(cmap_category + " colormaps", fontsize=14, y=1.0, x=0.6)
for ax, name in zip(axes, cmap_list):
# Get rgb values for colormap
rgb = cm.get_cmap(plt.get_cmap(name))(x)[np.newaxis, :, :3]
# Get colormap in CAM02-UCS colorspace. We want the lightness.
lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
L = lab[0, :, 0]
L = np.float32(np.vstack((L, L, L)))
ax[0].imshow(gradient, aspect="auto", cmap=plt.get_cmap(name))
ax[1].imshow(L, aspect="auto", cmap="binary_r", vmin=0.0, vmax=100.0)
pos = list(ax[0].get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3] / 2.0
fig.text(x_text, y_text, name, va="center", ha="right", fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax[0].set_axis_off()
ax[1].set_axis_off()
plt.show()
示例3: plot_images_with_probabilities
def plot_images_with_probabilities(images, predictiondistribution):
""" Show images along with their predicted distribution
INPUT:
images: the images
predictiondistribution: the output distribution of the network
"""
assert images.shape[0] == predictiondistribution.shape[0], "Number of images does not match the amount of prediction labels"
assert images.shape[0] <= 20, "Can't show more than 20 images"
fig, axarr = plt.subplots(images.shape[0], 2)
for i in range(0, images.shape[0], ):
#Plot the image itself
ax = axarr[i,0]
ax.imshow(images[i,:,:],
cmap=plt.get_cmap("gray_r"),
interpolation="none")
ax.axis("off")
#Plot the probability distribution
ax = axarr[i,1]
ax.imshow(np.expand_dims(predictiondistribution[i,:], 0),
cmap=plt.get_cmap("gray"),
interpolation="none",
vmin=0,
vmax=1)
ax.axes.get_xaxis().set_ticks(np.arange(10))
ax.axes.get_yaxis().set_ticks([])
plt.show()
示例4: demo_bottom_cbar
def demo_bottom_cbar(fig):
"""
A grid of 2x2 images with a colorbar for each column.
"""
grid = AxesGrid(fig, 121, # similar to subplot(132)
nrows_ncols = (2, 2),
axes_pad = 0.10,
share_all=True,
label_mode = "1",
cbar_location = "bottom",
cbar_mode="edge",
cbar_pad = 0.25,
cbar_size = "15%",
direction="column"
)
Z, extent = get_demo_image()
cmaps = [plt.get_cmap("autumn"), plt.get_cmap("summer")]
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest",
cmap=cmaps[i//2])
if i % 2:
cbar = grid.cbar_axes[i//2].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(True)
cax.axis[cax.orientation].set_label("Bar")
# This affects all axes as share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
示例5: test_linestrings_values
def test_linestrings_values(self):
from geopandas.plotting import plot_linestring_collection
fig, ax = plt.subplots()
# default colormap
coll = plot_linestring_collection(ax, self.lines, self.values)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
# specify colormap
coll = plot_linestring_collection(ax, self.lines, self.values,
cmap='RdBu')
fig.canvas.draw_idle()
cmap = plt.get_cmap('RdBu')
expected_colors = cmap(np.arange(self.N) / (self.N - 1))
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
# specify vmin/vmax
coll = plot_linestring_collection(ax, self.lines, self.values,
vmin=3, vmax=5)
fig.canvas.draw_idle()
cmap = plt.get_cmap()
expected_colors = cmap([0])
_check_colors(self.N, coll.get_color(), expected_colors)
ax.cla()
示例6: main
def main():
x, y, z = load_data()
print(z.shape)
# Fit a 3rd order, 2d polynomial
m = polyfit2d(x, y, z)
# Evaluate it on a grid...
nx, ny = 20, 20
xx, yy = np.meshgrid(np.linspace(x.min(), x.max(), nx),
np.linspace(y.min(), y.max(), ny))
zz = polyval2d(xx, yy, m)
# Plot
plt.imshow(zz,
origin='lower',
cmap=plt.get_cmap('hot'),
extent=[eta_min, eta_max, xi_min, xi_max],
aspect='auto')
m = cm.ScalarMappable(cmap=plt.get_cmap('hot'))
m.set_array(z)
plt.colorbar(m, label='memory capacity', ticks=[30, 40, 50, 60, 70, 80, 90, 100])
plt.xlabel(r'$\eta$', size=24)
plt.ylabel(r'$\xi$', size=24)
plt.savefig('eta_xi_mc_sampled.png')
plt.show()
开发者ID:pe-ge,项目名称:Computational-analysis-of-memory-capacity-in-echo-state-networks,代码行数:26,代码来源:plot2.py
示例7: plot_corrcoef_raftscope
def plot_corrcoef_raftscope(raftsfits, ROIrows, ROIcols, xylabels=None, title='', norm=True):
"""
Plot of correlation coefficients over list of CCD images.
:param raftsfits:
:param ROIrows: must be in the format: slice(start, stop)
:param ROIcols: must be in the format: slice(start, stop)
:param norm: if True, computes correlation coefficients; if not, returns covariances
:return:
"""
datadir, dataname = os.path.split(raftsfits[0])
dataname = os.path.splitext(dataname)[0]
a = corrcoef_raftscope(raftsfits, ROIrows, ROIcols, norm)
fig, ax = plt.subplots(figsize=(10, 8))
if norm:
cax = ax.imshow(a, cmap=plt.get_cmap('jet'), norm=mplcol.Normalize(vmax=1, clip=True), interpolation='nearest')
else:
cax = ax.imshow(a, cmap=plt.get_cmap('jet'), norm=mplcol.Normalize(vmax=20000, clip=True), interpolation='nearest')
if norm:
titlestr = "Correlation for %s"
else:
titlestr = "Covariances for %s"
if title:
ax.set_title(titlestr % title)
else:
ax.set_title(titlestr % dataname)
ax.set_xticks(np.arange(0, 16*len(raftsfits), 16))
ax.set_yticks(np.arange(0, 16*len(raftsfits), 16))
if xylabels:
ax.set_xticklabels(xylabels)
ax.set_yticklabels(xylabels)
cbar = fig.colorbar(cax, orientation='vertical')
plt.savefig(os.path.join(datadir, "corrscope-%s.png" % dataname))
plt.show()
示例8: Plot_Gen_Mass_Density
def Plot_Gen_Mass_Density(data_file='filtered_data'):
'''
Create a interpolated plot where the colors of the line
correspond to the mass transfer rate of the data
Parameters
----------
data_file : str
file to be used to generate the plot
'''
try:
filtered_results = np.loadtxt(data_file)
except:
root_dir = raw_input("file not found, select directory to generate: ")
filtered_results = mesa_calc.Gen_Filtered_Data_File(root_dir=root_dir)
filtered_period = filtered_results[:, 1]
filtered_mtransfer = filtered_results[:, 3]
filtered_mass1 = filtered_results[:, 4]
filtered_run_num = filtered_results[:, 13]
split_ind = np.where(filtered_run_num != 0)[0]
split_mass1 = np.split(filtered_mass1, split_ind)
split_period = np.split(filtered_period, split_ind)
split_mtransfer = np.split(filtered_mtransfer, split_ind)
plt.figure(1, figsize=(24, 13.5)) # 1920x1080
plt.clf()
if xrange(len(split_mass1)):
for sys_number in xrange(len(split_mass1)):
Plot_Color_Line(split_mass1[sys_number],
split_period[sys_number],
z=split_mtransfer[sys_number],
cmap=plt.get_cmap('jet'),
norm=plt.Normalize(-12, max(filtered_mtransfer)))
else:
Plot_Color_Line(split_mass1[0],
split_period[0],
z=split_mtransfer[0],
cmap=plt.get_cmap('jet'),
norm=plt.Normalize(-12, max(filtered_mtransfer)))
sm = plt.cm.ScalarMappable(cmap=plt.get_cmap('jet'),
norm=plt.Normalize(-12, max(filtered_mtransfer)))
sm._A = []
cb = plt.colorbar(sm)
cb.set_label(r'log$(\dot{M})$', size=20)
plt.xlabel(r'Donor Mass $(\dot{M_\odot})$', fontsize=20)
plt.ylabel(r'Period log(days)', fontsize=20)
plt.xlim(min(filtered_mass1) - 0.2, max(filtered_mass1) + 0.2)
plt.ylim(min(filtered_period) - 0.2, max(filtered_period) + 0.2)
plt.tick_params(axis='both', which='major', labelsize=20)
plt.grid()
figname = 'dt_mass_period'
plt.savefig(figname)
plt.show()
示例9: heat_map
def heat_map(self, cmap="RdYlGn", vmin=None, vmax=None, font_cmap=None):
if cmap is None:
carr = ["#d7191c", "#fdae61", "#ffffff", "#a6d96a", "#1a9641"]
cmap = LinearSegmentedColormap.from_list("default-heatmap", carr)
if isinstance(cmap, str):
cmap = get_cmap(cmap)
if isinstance(font_cmap, str):
font_cmap = get_cmap(font_cmap)
vals = self.actual_values.astype(float)
if vmin is None:
vmin = vals.min().min()
if vmax is None:
vmax = vals.max().max()
norm = (vals - vmin) / (vmax - vmin)
for ridx in range(self.nrows):
for cidx in range(self.ncols):
v = norm.iloc[ridx, cidx]
if np.isnan(v):
continue
color = cmap(v)
hex = rgb2hex(color)
styles = {"BACKGROUND": HexColor(hex)}
if font_cmap is not None:
styles["TEXTCOLOR"] = HexColor(rgb2hex(font_cmap(v)))
self.iloc[ridx, cidx].apply_styles(styles)
return self
示例10: DisplayFrames
def DisplayFrames(video):
num_rows = np.shape(video)[0]
num_cols = np.shape(video)[1]
num_frames = np.shape(video)[2]
f = 0
plt.imshow(video[:,:,f], cmap=plt.get_cmap('gray'))
plt.show(block=False)
while(True):
f = 0
print("\033[A \033[A")
x = input("Press f: forward, b: back, q: quit : ")
if (x == "f"):
if ((f+1) < num_frames):
f = f+1
elif (x == "b"):
if ((f-1) >= 0):
f = f-1
elif (x == "q"):
break
else:
f = f
plt.imshow(video[:,:,f], cmap=plt.get_cmap('gray'))
plt.show(block=False)
示例11: plot_coo_matrix
def plot_coo_matrix(m):
if not isinstance(m, coo_matrix):
m = coo_matrix(m)
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='black')
#print m.data
#print len(m.col), len(m.row), len(m.data)
cdata = array2cmap(m.data, -10, 10)
cmhot = plt.get_cmap("hot")
dgray = plt.get_cmap('gray')
#cnorm = colors.Normalize(vmin=-10, vmax=10)
#ax.scatter(m.col, m.row, c=m.data, cmap=cmhot)
ax.plot(m.col, m.row, 's', c="white", ms=1)
ax.set_xlim(0, m.shape[1])
ax.set_ylim(0, m.shape[0])
ax.set_aspect('equal')
for spine in ax.spines.values():
spine.set_visible(False)
ax.invert_yaxis()
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
return ax
示例12: _plot_2D
def _plot_2D(self, ax=None, plot_3D=True, **kwargs):
fig = plt.gcf()
if ax is None:
if plot_3D:
print HEEEEEEE
ax = fig.add_subplot(111, projection='3d')
else:
print HEYEHYE
ax = fig.add_subplot(111)
if hasattr(self,'probs'):
del self.probs
if not hasattr(self.softmax_collection, 'probs'):
self.softmax_collection.probability()
X = self.softmax_collection.X
Y = self.softmax_collection.Y
Z = self.softmax_collection.probs[:, self.id].reshape(X.shape[0], X.shape[1])
bounds = self.softmax_collection.bounds
if plot_3D:
ax.plot_surface(X, Y, Z, cstride=2, rstride=2, linewidth=0,
antialiased=False, cmap=plt.get_cmap(self.cmap))
ax.set_zlabel('Probability P(D=i|X)')
else:
levels = np.linspace(0, np.max(Z), 50)
ax.contourf(X, Y, Z, levels=levels, cmap=plt.get_cmap(self.cmap),
alpha=0.8)
ax.set_xlim(bounds[0], bounds[2])
ax.set_ylim(bounds[1], bounds[3])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Class Probabilities')
示例13: gradient
def gradient(figure_object, axis_object, xs, ys, start_year, TWP_length, cmap, key_count):
"""Based on http://matplotlib.org/examples/pylab_examples/multicolored_line.html
and http://stackoverflow.com/questions/19132402/set-a-colormap-under-a-graph
"""
from matplotlib.collections import LineCollection
# plot a color_map line fading to white
points = np.array([xs, ys]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=plt.get_cmap('gray'), norm=plt.Normalize(start_year, start_year+TWP_length),
linewidth=0.2, zorder=1) # norm sets the color min:max range
lc.set_array(np.array(xs))
axis_object.add_collection(lc)
# add fading color_map fill as well
xs.append(max(xs))
xs.append(min(xs))
ys.append(0)
ys.append(0)
poly, = axis_object.fill(xs, ys, facecolor='none', edgecolor='none')
img_data = np.arange(0, 100, 1)
img_data = img_data.reshape(1, img_data.size)
im = axis_object.imshow(img_data, aspect='auto', origin='lower', cmap=plt.get_cmap(cmap),
extent=[start_year+TWP_length, start_year, 1000, -1000], vmin=0., vmax=100., zorder=-(start_year+1)*key_count)
im.set_clip_path(poly)
示例14: createTrainingData
def createTrainingData(file = '/Users/oli/Proj_Large_Data/Deep_Learning_MRI/BRATS-2/brats2.h5', show=True):
lnum = 0
with h5py.File(file, 'r') as f:
for name in f:
t1c = np.asarray(f[name + '/' + 'VSD.Brain.XX.O.MR_T1c'])
pred = np.asarray(f[name + '/' + 'VSD.Brain_3more.XX.XX.OT'])
if show:
fig = plt.figure()
plt.title(name)
plt.xticks([])
plt.yticks([])
plt.subplots_adjust(hspace=1e-3, wspace=1e-3)
for i, z in enumerate(range(65, 145, 5)):
tc1s = (np.array(t1c[z, 20:180, 0:160], dtype='float32')).reshape(1,1,160,160)
preds = (np.array(pred[z, 20:180, 0:160], dtype='uint8')).reshape(1,1,160,160)
if (lnum == 0):
X = tc1s
Y = preds
else:
X = np.vstack((X, tc1s))
Y = np.vstack((Y, preds))
if show:
a = fig.add_subplot(6, 6, (2 * i + 1), xticks=[], yticks=[]) # NB the one based API sucks!
plt.imshow(X[lnum,0,:,:], cmap=plt.get_cmap('gray'))
a = fig.add_subplot(6, 6, (2 * i + 2), xticks=[], yticks=[]) # NB the one based API sucks!
plt.imshow(Y[lnum,0,:,:], cmap=plt.get_cmap('gray'))
lnum += 1
if show:
plt.pause(1)
return X,Y
示例15: plot_data
def plot_data(data,lon_data, lat_data, periodname, AODcatname,maptype,cmapname,minv=0,maxv=0,folder=""):
fig = plt.figure()
#ax = fig.add_axes([0.1,0.1,0.8,0.8])
m = Basemap(llcrnrlon=19,llcrnrlat=34,urcrnrlon=29,urcrnrlat=42,
resolution='h',projection='cass',lon_0=24,lat_0=38)
nx = int((m.xmax-m.xmin)/1000.)+1
ny = int((m.ymax-m.ymin)/1000.)+1
topodat = m.transform_scalar(data,lon_data,lat_data,nx,ny)
if minv<>0 or maxv<>0 :
im = m.imshow(topodat,cmap=plt.get_cmap(cmapname),vmin=minv,vmax=maxv)
else:
im = m.imshow(topodat,cmap=plt.get_cmap(cmapname))
m.drawcoastlines()
m.drawmapboundary()
m.drawcountries()
m.drawparallels(np.arange(35,42.,1.), labels=[1,0,0,1])
m.drawmeridians(np.arange(-20.,29.,1.), labels=[1,0,0,1])
cb = m.colorbar(im,"right", size="5%", pad='2%')
title=maptype+" AOD "+AODcatname+" "+periodname+" 2007-2014"
plt.title(title)
pylab.savefig(folder+maptype+"AOD"+AODcatname+"_"+periodname + ".png")