Python matplotlib.ticker 模块,MultipleLocator() 实例源码
我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用matplotlib.ticker.MultipleLocator()。
def showAttention(input_sentence, output_words, attentions):
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.numpy(), cmap='bone')
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([''] + input_sentence.split(' ') +
['<EOS>'], rotation=90)
ax.set_yticklabels([''] + output_words)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def __init__(self, cpu_histogram):
super().__init__()
# set up the graphical elements
layout = qgridLayout(self)
self.setLayout(layout)
fig = figure()
layout.addWidget(figureCanvas(fig))
# do the plotting
ax = fig.add_subplot(1, 1, 1) # 1x1 grid,first subplot
ax.set_title('cpu Usage Histogram (%s Cores/%s Threads)' % (psutil.cpu_count(False), psutil.cpu_count(True)))
ax.set_ylabel('Count')
ax.set_xlabel('cpu %')
ax.grid(True)
xs = range(0, 101)
ax.plot(xs, [cpu_histogram[x] for x in xs])
ax.xaxis.set_major_locator(MultipleLocator(10.))
self.show()
def plot_confusion_matrix(self):
# Calculate and create confusion matrix
conf_mat = np.zeros((len(self.categories.keys()),len(self.categories.keys())))
for idx in range(len(self.predictions_int)):
conf_mat[self.predictions_int[idx]][self.true_ys_int[idx]] += 1
for idx1 in range(conf_mat.shape[0]):
total = np.sum(conf_mat, axis=0)[idx1]
for idx2 in range(conf_mat.shape[1]):
conf_mat[idx1][idx2] = float(conf_mat[idx1][idx2]/total)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(conf_mat)
fig.colorbar(cax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
ax.set_xticklabels([''] + self.inv_categories.values(), rotation='vertical')
ax.set_yticklabels([''] + self.inv_categories.values())
plt.show()
def saveAttention(input_sentence, attentions, outpath):
# Set up figure with colorbar
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(24,10), )
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
fig.colorbar(cax)
if input_sentence:
# Set up axes
ax.set_yticklabels([' '] + list(input_sentence) + [' '])
# Show label at every tick
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.tight_layout()
plt.savefig(outpath)
plt.close('all')
def prettyPlot(samps, dat, hid):
fig, ax = plt.subplots()
sz = 18
plt.rc('xtick', labelsize=sz)
plt.rc('ytick', labelsize=sz)
ax.set_xticklabels([1]+samps, fontsize=sz)
ax.set_yticklabels([1]+samps[::-1], fontsize=sz)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
ax.set_xlabel('Number of Experts', fontsize=sz+2)
ax.set_ylabel('Minibatch Size', fontsize=sz+2)
ax.set_title('MOE Cell Speedup Factor', fontsize=sz+4)
#Show cell values
for i in range(len(samps)):
for j in range(len(samps)):
ax.text(i, j, str(dat[i,j])[:4], ha='center', va='center', fontsize=sz, color='white')
plt.imshow(cellTimes, cmap='viridis', norm=colors.Lognorm(vmin=cellTimes.min(), vmax=cellTimes.max()))
plt.show()
def show_attention(input_sentence, cmap='bone')
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([''] + input_sentence.split(' ') + ['<EOS>'], rotation=90)
ax.set_yticklabels([''] + output_words)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
show_plot_visdom()
plt.show()
plt.close()
def plot_attention(in_seq, out_seq, attentions):
""" From http://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html"""
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions, cmap='bone')
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([' '] + [str(x) for x in in_seq], rotation=90)
ax.set_yticklabels([' '] + [str(x) for x in out_seq])
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def showPlot(points):
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
######################################################################
# Evaluation
# ==========
#
# Evaluation is mostly the same as training,but there are no targets so
# we simply Feed the decoder's predictions back to itself for each step.
# Every time it predicts a word we add it to the output string,and if it
# predicts the EOS token we stop there. We also store the decoder's
# attention outputs for display later.
#
def showAttention(input_sentence, rotation=90)
ax.set_yticklabels([''] + output_words)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def draw_last_Z_range(self, my_ae, my_train):
my_period = np.int(np.log2(my_ae.epoch_limit) + 1)
dataW = my_ae.get_W1(my_period)
dataB = my_ae.get_b1(my_period)
rd = self.repdef['LastZfig']
ax4 = plt.subplot(self.gs[rd[0]:rd[0] + rd[2] + 1, rd[1]:(rd[1] + rd[3])])
x = range(len(dataW))
zshape = my_ae.encode_by_snap(dataW, dataB, my_train[my_ae.get_mnist_start_index(0) + self.var_offset])
zsum = np.zeros(zshape.shape)
for sample in range(10):
z = my_ae.encode_by_snap(dataW, my_train[my_ae.get_mnist_start_index(sample) + self.var_offset])
zsum += z
x = range(len(z))
ax4.plot(x, z + (9.0 - sample), label=str(sample))
ax4.plot(x, zsum, color="b", label="Sum")
ax4.legend(bBox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0, prop={'size' : 6})
ax4.set_xlabel("Last Z=f(Wx+b) Range fig. horiz axis=Node Number")
ax4.xaxis.set_minor_locator(tick.MultipleLocator(2))
ax4.yaxis.set_minor_locator(tick.MultipleLocator(1))
def percent_change_as_time_plot(adjusted_df, security):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date,Adjusted Close,and Percentage Change.
:param security: <SecurityInfo class> Holds information about the requested security
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
plt.xlabel("Dates")
plt.ylabel("Percentage change from last period")
if security.get_period() == "none":
plt.title("Percentage change in " + security.get_name(), y=1.03)
else:
plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
def percent_change_as_time_plot(adjusted_df):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date,and Percentage Change.
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, pct_change_list)
#ax.plot(date_list,adjusted_df["Adjusted Close"])
plt.xlabel("Years")
plt.ylabel("Percentage change from last week")
plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
def percent_change_as_time_plot(adjusted_df):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date,and Percentage Change.
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in adjusted_df['Date'].tolist()]
fig, pct_change_list)
plt.xlabel("Years")
plt.ylabel("Percentage change from last week")
plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
def savePlot(points, outpath):
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
plt.savefig(outpath)
plt.close('all')
######################################################################
# This is a helper function to print time elapsed and estimated time
# remaining given the current time and progress %.
#
def view_limits(self, dmin, dmax):
dmin, dmax = ticker.MultipleLocator.view_limits(self, dmax)
size = dmax - dmin
dmin -= size * self._left_margin
dmax += size * self._right_margin
return dmin, dmax
def format_axis(axis_in, major=None, minor=None, direction='out', position=''):
if axis_in == 'x':
axis = plt.gca().xaxis
elif axis_in == 'y':
axis = plt.gca().yaxis
if major != None:
axis.set_major_locator(MultipleLocator(major))
if minor != None:
axis.set_minor_locator(MultipleLocator(minor))
if len(direction) > 0:
axis.set_tick_params(which='both', direction=direction)
else:
axis.set_tick_params(which='both', direction='out')
if len(position) > 0:
axis.set_ticks_position(position)
else:
if axis_in == 'x':
axis.set_ticks_position('bottom')
else:
axis.set_ticks_position('left')
# This is a bit more of an advanced programming thing for my usage. I basically
# create objects for each data file and use them to keep track of the analysis
# progression and steps.
def display(curvelist):
"""
Take a list of curve and plot it according to its type
@type curvelist: list of curve
@param curvelist: list of curve for plotting
@todo: improve the display with legend,color...
"""
plt.figure(figsize=(12,8)) # sets figure size
axes = plt.gca()
# Something for astronomers only : we invert the y axis direction !
axes.set_ylim(axes.get_ylim()[::-1])
# Astronomers like minor tick marks :
minorxLocator = MultipleLocator(100)
for curve in curvelist:
if curve.type=="purelightcurve":
plt.plot(linspace(0,curve.length,curve.length*curve.res),curve.data)
if curve.type=="simlightcurve":
if curve.name=="A": plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.originalcurve.data+curve.dmag,color="black",label="Original curve")
plt.errorbar(curve.datatime,curve.datamagoff(),curve.dataerr,ls='None',marker='.',ecolor="#BBBBBB", color=curve.plotcolor,label=str(curve.name)+str(curve.shift))
plt.plot(np.linspace(0,curve.mlcurve.data+curve.dmag,color=curve.plotcolor)#,label="microlensing for "+str(curve.name))
plt.xlabel('time [j]')
plt.ylabel('Magnitude ')
plt.legend( numpoints = 1, prop = fm.FontProperties(size = 10))
plt.show()
def draw_last_Wb_range(self, my_train):
my_period = np.int(np.log2(my_ae.epoch_limit) + 1)
dataW = my_ae.get_W1(my_period)
dataB = my_ae.get_b1(my_period)
rd = self.repdef['LastWRangefig']
ax3 = plt.subplot(self.gs[rd[0]:rd[0] + rd[2] + 1, rd[1]:(rd[1] + rd[3])])
ax3tw = ax3.twinx()
x = range(len(dataW))
y_mean = np.array([])
y_max = np.array([])
y_min = np.array([])
for i in x:
y_mean = np.append(y_mean, np.array(np.mean([dataW[i]])))
y_max = np.append(y_max, np.array(np.max([dataW[i]])))
y_min = np.append(y_min, np.array(np.min([dataW[i]])))
y_low = y_mean - y_min
y_up = y_max - y_mean
a_err = [y_low, y_up]
ax3.errorbar(x, y_mean, yerr=a_err, label="W")
ax3tw.plot(x, 'd', markersize=4, markerfacecolor='blue', label="b")
# ax2.set_title("Cost/Epoch",horizontalalignment='left',verticalalignment='bottom')
ax3.set_ylabel("W Min/Mean/max")
ax3.set_xlabel("Last W Range & b Bias fig. horiz axis=Node Number")
ax3.set_xlim(-1, len(y_mean))
#Reset Y Limit (Adjust Zero Lebel)
#w_limit = math.ceil(np.max((np.max(dataW),-np.min(dataW))))
w_limit = np.max((np.max(dataW), -np.min(dataW)))
ax3.set_ylim(-w_limit, w_limit)
#b_limit = math.ceil(np.max((np.max(dataB),-np.min(dataB))))
b_limit = np.max((np.max(dataB), -np.min(dataB))) + 0.2
ax3tw.set_ylim(-b_limit, b_limit)
ax3tw.set_ylabel("b Bias plot")
ax3.legend(bBox_to_anchor=(1.11, 0.0), loc='lower left', prop={'size': 8})
ax3tw.legend(bBox_to_anchor=(1.11, 1.0), prop={'size': 8})
ax3.xaxis.set_minor_locator(tick.MultipleLocator(2))
print(" fig. W Min/Mean/Max")
def plot_fisher_data(self, fisher_data, axes=None, fig=None,
linestyles=[], labels=[]):
"""
Args:
fisher_dat(tuple): Data from the fisher_decomposition function
*see docscring for deFinition*
Keyword Args:
axes(plt.Axes): *Ignored*
fig(plt.figure): A valid figure to plot on
linestyles(list): A list of valid linestyles *Ignored*
labels(list): A list of labels *Ignored*
"""
if fig is None:
fig = plt.figure()
else:
pass
# end
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
eigs = fisher_data[0]
eig_vects = fisher_data[1]
eig_func = fisher_data[2]
indep = fisher_data[3]
# ax1.bar(np.arange(eigs.shape[0]),eigs,width=0.9,color='black',
# edgecolor='none',orientation='vertical')
ax1.semilogy(eigs, 'sk')
ax1.set_xlabel("Eigenvalue number")
ax1.set_ylabel(r"Eigenvalue / Pa$^{-2}$")
ax1.set_xlim(-0.5, len(eigs) - 0.5)
ax1.set_ylim([0.1 * min(eigs[np.nonzero(eigs)]), 10 * max(eigs)])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
styles = ['-g', '-.b', '--m', ':k', '-c', '-.y', '--r'] *\
int(math.ceil(eig_func.shape[0] / 7.0))
for i in range(eig_func.shape[0]):
ax2.plot(indep, eig_func[i], styles[i],
label="{:d}".format(i))
# end
ax2.legend(loc='best')
ax2.get_legend().set_title("Eigen-\nfunctions", prop={'size': 7})
ax2.set_xlabel(r"Specific volume / cm$^3$ g$^{-1}$")
ax2.set_ylabel("Eigenfunction response / Pa")
fig.tight_layout()
return fig
def plot_convergence(self, hist, linestyles=['-k'], labels=[]):
"""
Args:
hist(tuple): Convergence history,elements
0. (list): MAP history
1. (list): DOF history
Keyword Args:
axes(plt.Axes): The axes on which to plot the figure,if None,
creates a new figure object on which to plot.
linestyles(list): Strings for the linestyles
labels(list): Strings for the labels
"""
if axes is None:
fig = plt.figure()
ax1 = fig.gca()
else:
fig = None
ax1 = axes
# end
ax1.semilogy(-np.array(hist[0]), linestyles[0])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax1.set_xlabel('Iteration number')
ax1.set_ylabel('Negative a posteriori log likelihood')
# fig = plt.figure()
# ax1 = fig.add_subplot(121)
# ax2 = fig.add_subplot(122)
# for i in range(dof_hist.shape[1]):
# ax1.plot(dof_hist[:,i]/dof_hist[0,i])
# # end
# fig.suptitle('Convergence of iterative process')
# ax1.set_ylabel('Spline knot value')
# ax1.set_xlabel('Iteration number')
# fig.savefig('EOS_convergence.pdf')
def plot_fisher_matrix(sens_matrix, exp, model, fig, lines=None):
"""
"""
fisher = exp.get_fisher_matrix(sens_matrix)
fisher_data = Bayesian.fisher_decomposition(fisher, tol=1E-3)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
eigs = fisher_data[0]
eig_vects = fisher_data[1]
eig_func = fisher_data[2]
indep = fisher_data[3]
ax1.semilogy(eigs, 'sk')
ax1.set_xlabel("Eigenvalue number")
ax1.set_ylabel(r"Eigenvalue / Pa$^{-2}$")
ax1.set_xlim(-0.5, len(eigs) - 0.5)
ax1.set_ylim([0.1 * min(eigs[np.nonzero(eigs)]), 10 * max(eigs)])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
styles = ['-g', '--r'] *\
int(math.ceil(eig_func.shape[0] / 7.0))
for i in range(eig_func.shape[0]):
ax2.plot(indep,
label="{:d}".format(i))
# end
# find rho=25.77 gpa
for line, name in lines:
ax2.axvline(line)
# end
ax2.legend(loc='best')
ax2.get_legend().set_title("Eigen-\nfunctions", prop={'size': 7})
ax2.set_xlabel(r"Density / g cm$^{-3}$ ")
ax2.set_ylabel("Eigenfunction response / Pa")
fig.tight_layout()
return fig
def plot_results(load_folders, save_folder):
df_rmse, df_task_net = load_results(load_folders)
rmse_mean, rmse_stds = get_means_stds(df_rmse)
task_mean, task_stds = get_means_stds(df_task_net)
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.set_size_inches(8.5, 3)
styles = [ ':', '--', ':', '-']
colors = [sns.color_palette()[i] for i in [4,2,3,1]]
ax = axes[0]
ax.set_axis_bgcolor("none")
for col, style, color in zip(rmse_mean.columns, styles, colors):
rmse_mean[col].plot(
ax=ax, lw=2, fmt=style, color=color, yerr=rmse_stds[col])
ax.set_ylabel('RMSE')
ax2 = axes[1]
ax2.set_axis_bgcolor("none")
for col, color in zip(task_mean.columns, colors):
task_mean[col].plot(
ax=ax2, yerr=task_stds[col])
ax2.set_ylabel('Task Loss')
plt.tight_layout()
plt.subplots_adjust(bottom=0.3)
for a in [ax, ax2]:
a.margins(0,0)
a.grid(linestyle=':', linewidth='0.5', color='gray')
a.xaxis.set_major_locator(ticker.MultipleLocator(4))
a.set_xlim(0, 24)
a.set_ylim(0, )
# Joint x-axis label and legend
fig.text(0.5, 0.13, 'Hour of Day', fontsize=11)
legend = ax.legend(loc='center left', bBox_to_anchor=(0, -0.4),
shadow=False, ncol=7, fontsize=11, borderpad=0, frameon=False)
fig.savefig(os.path.join(save_folder,
'{}.pdf'.format(save_folder)), dpi=100, encoding='pdf')
def gen_ellip(h, k, a, b, mu, graph=True):
'''
--------------------------------------------------------------------
This plots the general functional form of an ellipse and highlights
the upper-right quadrant.
[([x - h] / a) ** mu] + [([y - k] / b) ** mu] = 1
--------------------------------------------------------------------
INPUTS:
h = scalar,x-coordinate of centroid (h,k)
k = scalar,y-coordinate of centroid (h,k)
a = scalar > 0,horizontal radius of ellipse
b = scalar > 0,vertical radius of ellipse
mu = scalar > 0,curvature parameter of ellipse
graph = boolean,=True if graph output
OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None
OBJECTS CREATED WITHIN FUNCTION:
N = integer > 0,number of elements in the support of x
xvec = (N,) vector,support of x variable
yvec = (N,values of y corresponding to the upper-right
quadrant values of the ellipse from xvec
FILES CREATED BY THIS FUNCTION:
images/EllipseGen.png
RETURNS: xvec,yvec
--------------------------------------------------------------------
'''
N = 1000
xvec = np.linspace(h, h + a, N)
yvec = b * ((1 - (((xvec - h) / a) ** mu)) ** (1 / mu)) + k
if graph:
e1 = Ellipse((h, k), 2 * a, 2 * b, 360.0, linewidth=2.0,
fill=False, label='Full ellipse')
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.add_patch(e1)
plt.plot(xvec, yvec, color='r', linewidth=4,
label='Upper-right quadrant')
# for the minor ticks,use no labels; default NullFormatter
minorLocator = MultipleLocator(1)
ax.xaxis.set_minor_locator(minorLocator)
plt.grid(b=True, which='major', color='0.65', linestyle='-')
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.xlim((h - 1.6 * a, h + 1.6 * a))
plt.ylim((k - 1.4 * b, k + 1.4 * b))
# plt.legend(loc='upper right')
figname = "images/EllipseGen"
plt.savefig(figname)
print("Saved figure: " + figname)
# plt.show()
plt.close()
return xvec, yvec