Python matplotlib.pylab 模块,colorbar() 实例源码
我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用matplotlib.pylab.colorbar()。
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
from matplotlib import pylab
cm = np.asarray(cm, dtype=np.float32)
for i, row in enumerate(cm):
cm[i] = cm[i] / np.sum(cm[i])
#import matplotlib.pyplot as plt
#plt.ion()
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(label_list)))
ax.set_xticklabels(label_list, rotation='vertical')
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks(range(len(label_list)))
ax.set_yticklabels(label_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig('test.jpg')
pylab.show()
def plot_confusion_matrix(cm, genre_list, name, title):
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(genre_list)))
ax.set_xticklabels(genre_list)
ax.xaxis.set_ticks_position("bottom")
ax.set_yticks(range(len(genre_list)))
ax.set_yticklabels(genre_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.show()
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig(
os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight")
def plot_confusion_matrix(cm, plot_title, filename, genres=None):
if not genres:
genres = GENRES
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=100.0)
axes = pylab.axes()
axes.set_xticks(range(len(genres)))
axes.set_xticklabels(genres, rotation=45)
axes.set_yticks(range(len(genres)))
axes.set_yticklabels(genres)
axes.xaxis.set_ticks_position("bottom")
pylab.title(plot_title, fontsize=14)
pylab.colorbar()
pylab.xlabel('Predicted class', fontsize=12)
pylab.ylabel('Correct class', fontsize=12)
pylab.grid(False)
#pylab.show()
pylab.savefig(os.path.join(PLOTS_DIR, "cm_%s.eps" % filename), bbox_inches="tight")
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
from matplotlib import pylab
cm = np.asarray(cm, dtype=np.float32)
for i, row in enumerate(cm):
cm[i] = cm[i] / np.sum(cm[i])
#import matplotlib.pyplot as plt
#plt.ion()
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(label_list)))
ax.set_xticklabels(label_list, rotation='vertical')
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks(range(len(label_list)))
ax.set_yticklabels(label_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig('test.jpg')
pylab.show()
def draw(m, name, extra=None):
FIG.clf()
matrix = m
orig_shape = np.shape(matrix)
# lose the channel shape in the end of orig_shape
new_shape = orig_shape[:-1]
matrix = np.reshape(matrix, new_shape)
ax = FIG.add_subplot(1,1,1)
ax.set_aspect('equal')
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.gray)
# plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
if extra != None:
greens, reds = extra
grn_x, grn_y, = greens
red_x, red_y = reds
plt.scatter(x=grn_x, y=grn_y, c='g', s=40)
plt.scatter(x=red_x, y=red_y, c='r', s=40)
# # put a blue dot at (10, 20)
# plt.scatter([10], [20])
# # put a red dot, size 40, at 2 locations:
# plt.scatter(x=[3, 4], y=[5, 6], c='r', s=40)
# # plt.plot()
plt.savefig(name)
def draw(m, name, extra=None):
FIG.clf()
matrix = m
orig_shape = np.shape(matrix)
# lose the channel shape in the end of orig_shape
new_shape = orig_shape[:-1]
matrix = np.reshape(matrix, new_shape)
ax = FIG.add_subplot(1,1,1)
ax.set_aspect('equal')
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.gray)
# plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
if extra != None:
greens, reds = extra
grn_x, grn_y, = greens
red_x, red_y = reds
plt.scatter(x=grn_x, y=grn_y, c='g', s=40)
plt.scatter(x=red_x, y=red_y, c='r', s=40)
# # put a blue dot at (10, 20)
# plt.scatter([10], [20])
# # put a red dot, size 40, at 2 locations:
# plt.scatter(x=[3, 4], y=[5, 6], c='r', s=40)
# # plt.plot()
plt.savefig(name)
def draw(m, name, extra=None):
FIG.clf()
matrix = m
orig_shape = np.shape(matrix)
# lose the channel shape in the end of orig_shape
new_shape = orig_shape[:-1]
matrix = np.reshape(matrix, new_shape)
ax = FIG.add_subplot(1,1,1)
ax.set_aspect('equal')
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.gray)
# plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
if extra != None:
greens, reds = extra
grn_x, grn_y, = greens
red_x, red_y = reds
plt.scatter(x=grn_x, y=grn_y, c='g', s=40)
plt.scatter(x=red_x, y=red_y, c='r', s=40)
# # put a blue dot at (10, 20)
# plt.scatter([10], [20])
# # put a red dot, size 40, at 2 locations:
# plt.scatter(x=[3, 4], y=[5, 6], c='r', s=40)
# # plt.plot()
plt.savefig(name)
def plot_earth_model(self,type='perturbation'):
if(type=='model'):
plt.pcolor(self.theta, self.radius, self.vs_array)
plt.colorbar()
plt.show()
elif(type=='perturbation'):
plt.pcolor(self.theta, self.radius, self.dvs_array)
plt.colorbar()
plt.show()
def plot_model_no_control(model, plot_title='', name_suffix=''):
# plot function
mx, vx = model.get_posterior_x()
mins = np.min(mx, axis=0) - 0.5
maxs = np.max(mx, axis=0) + 0.5
nGrid = 50
xspaced = np.linspace(mins[0], maxs[0], nGrid)
yspaced = np.linspace(mins[1], maxs[1], nGrid)
xx, yy = np.meshgrid(xspaced, yspaced)
Xplot = np.vstack((xx.flatten(), yy.flatten())).T
mf, vf = model.predict_f(Xplot)
fig = plt.figure()
plt.imshow((mf[:, 0]).reshape(*xx.shape),
vmin=mf.min(), vmax=mf.max(), origin='lower',
extent=[mins[0], maxs[0], mins[1], maxs[1]], aspect='auto')
plt.colorbar()
plt.contour(
xx, yy, (mf[:, 0]).reshape(*xx.shape),
colors='k', linewidths=2, zorder=100)
zu = model.dyn_layer.zu
plt.plot(zu[:, 0], zu[:, 1], 'wo', mew=0, ms=4)
for i in range(mx.shape[0] - 1):
plt.plot(mx[i:i + 2, 0], mx[i:i + 2, 1],
'-bo', ms=3, linewidth=2, zorder=101)
plt.xlabel(r'$x_{t, 1}$')
plt.ylabel(r'$x_{t, 2}$')
plt.xlim([mins[0], maxs[0]])
plt.ylim([mins[1], maxs[1]])
plt.title(plot_title)
plt.savefig('/tmp/hh_gpssm_dim_0' + name_suffix + '.pdf')
fig = plt.figure()
plt.imshow((mf[:, 1]).reshape(*xx.shape),
vmin=mf.min(), vmax=mf.max(), origin='lower',
extent=[mins[0], maxs[0], mins[1], maxs[1]], aspect='auto')
plt.colorbar()
plt.contour(
xx, yy, (mf[:, 1]).reshape(*xx.shape),
colors='k', linewidths=2, zorder=100)
zu = model.dyn_layer.zu
plt.plot(zu[:, 0], zu[:, 1], 'wo', mew=0, ms=4)
for i in range(mx.shape[0] - 1):
plt.plot(mx[i:i + 2, 0], mx[i:i + 2, 1],
'-bo', ms=3, linewidth=2, zorder=101)
plt.xlabel(r'$x_{t, 1}$')
plt.ylabel(r'$x_{t, 2}$')
plt.xlim([mins[0], maxs[0]])
plt.ylim([mins[1], maxs[1]])
plt.title(plot_title)
plt.savefig('/tmp/hh_gpssm_dim_1' + name_suffix + '.pdf')
def plot_2d(params_dir):
model_dirs = [name for name in os.listdir(params_dir)
if os.path.isdir(os.path.join(params_dir, name))]
if len(model_dirs) == 0:
model_dirs = [params_dir]
colors = plt.get_cmap('plasma')
plt.figure(figsize=(20, 10))
ax = plt.subplot(111)
ax.set_xlabel('Learning Rate')
ax.set_ylabel('Error rate')
i = 0
for model_dir in model_dirs:
model_df = pd.DataFrame()
for param_path in glob.glob(os.path.join(params_dir,
model_dir) + '/*.h5'):
param = dd.io.load(param_path)
gd = {'learning rate': param['hyperparameters']['learning_rate'],
'momentum': param['hyperparameters']['momentum'],
'dropout': param['hyperparameters']['dropout'],
'val. objective': param['best_epoch']['validate_objective']}
model_df = model_df.append(pd.DataFrame(gd, index=[0]),
ignore_index=True)
if i != len(model_dirs) - 1:
ax.scatter(model_df['learning rate'],
model_df['val. objective'],
s=128,
marker=(i+3, 0),
edgecolor='black',
linewidth=model_df['dropout'],
label=model_dir,
c=model_df['momentum'],
cmap=colors)
else:
im = ax.scatter(model_df['learning rate'],
model_df['val. objective'],
s=128,
marker=(i+3, 0),
edgecolor='black',
linewidth=model_df['dropout'],
label=model_dir,
c=model_df['momentum'],
cmap=colors)
i += 1
plt.colorbar(im, label='Momentum')
plt.legend()
plt.show()
plt.savefig('{}.eps'.format(os.path.join(IMAGES_DIRECTORY, 'params2d')), format='eps', dpi=1000)
plt.close()
def plot_waterfall(fil, f_start=None, f_stop=None, if_id=0, logged=True,cb=False,freq_label=False,MJD_time=False, **kwargs):
""" Plot waterfall of data
Args:
f_start (float): start frequency, in MHz
f_stop (float): stop frequency, in MHz
logged (bool): Plot in linear (False) or dB units (True),
cb (bool): for plotting the colorbar
kwargs: keyword args to be passed to matplotlib imshow()
"""
matplotlib.rc('font', **font)
plot_f, plot_data = fil.grab_data(f_start, f_stop, if_id)
# Make sure waterfall plot is under 4k*4k
dec_fac_x, dec_fac_y = 1, 1
if plot_data.shape[0] > MAX_IMSHOW_POINTS[0]:
dec_fac_x = plot_data.shape[0] / MAX_IMSHOW_POINTS[0]
if plot_data.shape[1] > MAX_IMSHOW_POINTS[1]:
dec_fac_y = plot_data.shape[1] / MAX_IMSHOW_POINTS[1]
plot_data = rebin(plot_data, dec_fac_x, dec_fac_y)
if MJD_time:
extent=(plot_f[0], plot_f[-1], fil.timestamps[-1], fil.timestamps[0])
else:
extent=(plot_f[0], plot_f[-1], (fil.timestamps[-1]-fil.timestamps[0])*24.*60.*60, 0.0)
this_plot = plt.imshow(plot_data,
aspect='auto',
rasterized=True,
interpolation='nearest',
extent=extent,
cmap='viridis_r',
**kwargs
)
if cb:
plt.colorbar()
if freq_label:
plt.xlabel("Frequency [Hz]",fontdict=font)
if MJD_time:
plt.ylabel("Time [MJD]",fontdict=font)
else:
plt.ylabel("Time [s]",fontdict=font)
return this_plot