本文整理汇总了Python中matplotlib.pyplot.savefig函数的典型用法代码示例。如果您正苦于以下问题:Python savefig函数的具体用法?Python savefig怎么用?Python savefig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了savefig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_fish
def make_fish(zoom=False):
plt.close(1)
plt.figure(1, figsize=(6, 4))
plt.plot(plot_limits['pitch'], plot_limits['rolldev'], '-g', lw=3)
plt.plot(plot_limits['pitch'], -plot_limits['rolldev'], '-g', lw=3)
plt.plot(pitch.midvals, roll.midvals, '.b', ms=1, alpha=0.7)
p, r = make_ellipse() # pitch, off nominal roll
plt.plot(p, r, '-c', lw=2)
gf = -0.08 # Fudge on pitch value for illustrative purposes
plt.plot(greta['pitch'] + gf, -greta['roll'], '.r', ms=1, alpha=0.7)
plt.plot(greta['pitch'][-1] + gf, -greta['roll'][-1], 'xr', ms=10, mew=2)
if zoom:
plt.xlim(46.3, 56.1)
plt.ylim(4.1, 7.3)
else:
plt.ylim(-22, 22)
plt.xlim(40, 180)
plt.xlabel('Sun pitch angle (deg)')
plt.ylabel('Sun off-nominal roll angle (deg)')
plt.title('Mission off-nominal roll vs. pitch (5 minute samples)')
plt.grid()
plt.tight_layout()
plt.savefig('fish{}.png'.format('_zoom' if zoom else ''))
示例2: draw_ranges_for_parameters
def draw_ranges_for_parameters(data, title='', save_path='./pictures/'):
parameters = data.columns.values.tolist()
# remove flight name parameter
for idx, parameter in enumerate(parameters):
if parameter == 'flight_name':
del parameters[idx]
flight_names = np.unique(data['flight_name'])
print len(flight_names)
for parameter in parameters:
plt.figure()
axis = plt.gca()
# ax.set_xticks(numpy.arange(0,1,0.1))
axis.set_yticks(flight_names)
axis.tick_params(labelright=True)
axis.set_ylim([94., 130.])
plt.grid()
plt.title(title)
plt.xlabel(parameter)
plt.ylabel('flight name')
colors = iter(cm.rainbow(np.linspace(0, 1,len(flight_names))))
for flight in flight_names:
temp = data[data.flight_name == flight][parameter]
plt.plot([np.min(temp), np.max(temp)], [flight, flight], c=next(colors), linewidth=2.0)
plt.savefig(save_path+title+'_'+parameter+'.jpg')
plt.close()
示例3: plot_scatter_matrix
def plot_scatter_matrix(df, plotdir):
"Plot scatter matrix."
print('plotting scatter matrix, this may take a while')
plt.clf()
pd_scatter_matrix(df, figsize=(16,16))
plt.suptitle("Scatter Matrix", fontsize=14)
plt.savefig(plotdir + 'scatter_matrix.png')
示例4: Test
def Test(self):
test_Dir = "Result";
if not os.path.exists(test_Dir):
os.makedirs(test_Dir);
test_Label_List = [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5];
test_Label_Pattern = np.zeros((16, 10));
test_Label_Pattern[np.arange(16), test_Label_List] = 1;
feed_Dict = {
self.noise_Placeholder: np.random.uniform(-1., 1., size=[16, self.noise_Size]),
self.label_for_Fake_Placeholder: test_Label_Pattern,
self.is_Training_Placeholder: False
}; #Batch is constant in the test.
global_Step, mnist_List = self.tf_Session.run(self.test_Tensor_List, feed_dict = feed_Dict);
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
gs.update(wspace=0.05, hspace=0.05)
for index, mnist in enumerate(mnist_List):
ax = plt.subplot(gs[index])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(mnist.reshape(28, 28), cmap='Greys_r')
plt.savefig('%s/S%d.png' % (test_Dir, global_Step), bbox_inches='tight');
plt.close();
示例5: do_plot
def do_plot(mode, content, wide):
global style
style.apply(mode, content, wide)
data = np.load("data/prr_AsAu_%s%s.npz"%(content, wide))
AU, TAU = np.meshgrid(-data["Au_range_dB"], data["tau_range"])
Zu = data["PRR_U"]
Zs = data["PRR_S"]
assert TAU.shape == AU.shape == Zu.shape, "The inputs TAU, AU, PRR_U must have the same shape for plotting!"
plt.clf()
if mode in ("sync",):
# Plot the inverse power ratio, sync signal is stronger for positive ratios
CSf = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower")
CS2 = plt.contour(CSf, colors = ("r",)*5+("w",), linewidths=(0.75,)*5+(1.0,), origin="lower", hold="on")
else:
CSf = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower")
CS2f = plt.contour(CSf, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0), colors=4*("r",)+("w",), linewidths=(0.75,)*4+(1.0,), origin="lower", hold="on")
#CS2f = plt.contour(TAU, -AU, Zu, levels=(0.9, 1.0), colors=("0.0",), linewidths=(1.0,), origin="lower", hold="on")
if content in ("unif",):
CSu = plt.contourf(TAU, AU, Zu, levels=(0.2, 1.0), hatches=("////",), colors=("0.75",), origin="lower")
CS2 = plt.contour(CSu, levels=(0.2,), colors = ("r",), linewidths=(1.0,), origin="lower", hold="on")
style.annotate(mode, content, wide)
plt.axis([data["tau_range"][0], data["tau_range"][-1], -data["Au_range_dB"][-1], -data["Au_range_dB"][0]])
plt.ylabel(r"Signal power ratio ($\mathrm{SIR}$)", labelpad=2)
plt.xlabel(r"Time offset $\tau$ ($/T$)", labelpad=2)
plt.savefig("pdf/prrc2_%s_%s%s_z.pdf"%(mode, content, wide))
示例6: compare_chebhist
def compare_chebhist(dname, mylambda, c, Nbin = 25):
if mylambda == 'Do not exist':
print('--!!Warning: eig file does not exist, can not display compare histgram')
else:
mylambda = 1 - mylambda
lmin = max(min(mylambda), -1)
lmax = min(max(mylambda), 1)
# print c
cheb_file_content = '\n'.join([str(st) for st in c])
x = np.linspace(lmin, lmax, Nbin + 1)
y = plot_chebint(c, x)
u = (x[1:] + x[:-1]) / 2
v = y[1:] - y[:-1]
plt.clf()
plt.hold(True)
plt.hist(mylambda,Nbin)
plt.plot(u, v, "r.", markersize=10)
plt.hold(False)
plt.show()
filename = 'data/' + dname + '.png'
plt.savefig(filename)
cheb_filename = 'data/' + dname + '.cheb'
f = open(cheb_filename, 'w+')
f.write(cheb_file_content)
f.close()
示例7: default_run
def default_run(self):
"""
Plots the results, saves the figure, and finally displays it from simulating codewords with Sum-prod and Max-prod
algorithms across variance levels. This combines the results in one plot.
:return:
"""
if not os.path.exists("./graphs"):
os.makedirs("./graphs")
self.save_time = str(int(time.time()))
self.simulate(Decoder.SUM_PROD)
self.compute_error()
plt.plot([math.log10(x) for x in self.variance_levels], [math.log10(y) for y in self.bit_error_probability],
"ro-", label="Sum-Prod")
self.simulate(Decoder.MAX_PROD)
self.compute_error()
plt.plot([math.log10(x) for x in self.variance_levels], [math.log10(y) for y in self.bit_error_probability],
"g^--", label="Max-Prod")
plt.legend(loc=2)
plt.title("Hamming Decoder Factor Graph Simulation Results\n" +
r"$\log_{10}(\sigma^2)$ vs. $\log_{10}(P_e)$" + " for Max-Prod & Sum-Prod Algorithms\n" +
"Sample Size n = %(codewords)s Codewords \n Variance Levels = %(levels)s"
% {"codewords": str(self.iterations), "levels": str(self.variance_levels)})
plt.xlabel("$\log_{10}(\sigma^2)$")
plt.ylabel(r"$\log_{10}(P_e)$")
plt.savefig("graphs/%(time)s-max-prod-sum-prod-%(num_codewords)s-codewords-variance-bit_error_probability.png" %
{"time": self.save_time,
"num_codewords": str(self.iterations)}, bbox_inches="tight")
plt.show()
示例8: main
def main():
parser = argparse.ArgumentParser(description="""Compute subset of users who rated at
least 10 movies and plot fraction of users satisfied
as a function of inventory size.""")
parser.add_argument("infilename",
help="Read from this file.", type=open)
args = parser.parse_args()
ratings = read_inputs(args.infilename)
ratings = ratings.drop("timestamp", axis=1)
movie_rankings = find_movie_rankings(ratings)
ratings = ratings.drop("rating", axis=1)
user_rankings = find_user_rankings(ratings, movie_rankings)
num_users = user_rankings.user_id.unique().size
num_movies = movie_rankings.shape[0]
user_rankings = clean_rankings(user_rankings)
us_levels_100 = find_satisfaction(user_rankings, num_users, num_movies)
us_levels_90 = find_satisfaction(user_rankings, num_users, num_movies, satisfaction_level=0.9)
rc('text', usetex=True)
plt.title('Percent of Users Satisfied vs Inventory Size in the MovieLens Dataset')
plt.xlabel('Inventory Size')
plt.ylabel('Percent of Users Satisfied')
plt.plot(us_levels_100, 'b', label=r'$100\% \ satisfaction$')
plt.plot(us_levels_90, 'r--', label=r'$90\% \ satisfaction$')
plt.legend()
d = datetime.datetime.now().isoformat()
plt.savefig('user_satisfaction_%s.png' % d)
示例9: plot_wav_fft
def plot_wav_fft(wav_filename, desc=None):
plt.clf()
plt.figure(num=None, figsize=(6, 4))
sample_rate, X = scipy.io.wavfile.read(wav_filename)
spectrum = np.fft.fft(X)
freq = np.fft.fftfreq(len(X), 1.0 / sample_rate)
plt.subplot(211)
num_samples = 200.0
plt.xlim(0, num_samples / sample_rate)
plt.xlabel("time [s]")
plt.title(desc or wav_filename)
plt.plot(np.arange(num_samples) / sample_rate, X[:num_samples])
plt.grid(True)
plt.subplot(212)
plt.xlim(0, 5000)
plt.xlabel("frequency [Hz]")
plt.xticks(np.arange(5) * 1000)
if desc:
desc = desc.strip()
fft_desc = desc[0].lower() + desc[1:]
else:
fft_desc = wav_filename
plt.title("FFT of %s" % fft_desc)
plt.plot(freq, abs(spectrum), linewidth=5)
plt.grid(True)
plt.tight_layout()
rel_filename = os.path.split(wav_filename)[1]
plt.savefig("%s_wav_fft.png" % os.path.splitext(rel_filename)[0],
bbox_inches='tight')
示例10: 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
示例11: plot_dpi_dpr_distribution
def plot_dpi_dpr_distribution(args, dpis, dprs, diagnoses):
print log.INFO, 'Plotting estimate distributions...'
diagnoses = np.array(diagnoses)
diagnoses[(0.25 <= diagnoses) & (diagnoses <= 0.75)] = 0.5
# Setup plot
fig, ax = plt.subplots()
pt.setup_axes(plt, ax)
biomarkers_str = args.method if args.biomarkers is None else ', '.join(args.biomarkers)
ax.set_title('DP estimation using {0} at {1}'.format(biomarkers_str, ', '.join(args.visits)))
ax.set_xlabel('DP')
ax.set_ylabel('DPR')
plt.scatter(dpis, dprs, c=diagnoses, edgecolor='none', s=25.0,
vmin=0.0, vmax=1.0, cmap=pt.progression_cmap,
alpha=0.5)
# Plot legend
# noinspection PyUnresolvedReferences
rects = [mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_cn + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_mci + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_ad + (0.5,), linewidth=0)]
labels = ['CN', 'MCI', 'AD']
legend = ax.legend(rects, labels, fontsize=10, ncol=len(rects), loc='upper center', framealpha=0.9)
legend.get_frame().set_edgecolor((0.6, 0.6, 0.6))
# Draw or save the plot
plt.tight_layout()
if args.plot_file is not None:
plt.savefig(args.plot_file, transparent=True)
else:
plt.show()
plt.close(fig)
示例12: make_entity_plot
def make_entity_plot(filename, title, fixed_noip, fixed_ip, dynamic_noip, dynamic_ip):
plt.figure(figsize=(12,5))
plt.title("Settings comparison - " + title)
plt.xlabel('Time (ms)', fontsize=12)
plt.xlim([0,62000])
x = 0
barwidth = 0.5
bargroupspacing = 1.5
fixed_noip_mean,fixed_noip_conf = conf_stats(fixed_noip)
fixed_ip_mean,fixed_ip_conf = conf_stats(fixed_ip)
dynamic_noip_mean,dynamic_noip_conf = conf_stats(dynamic_noip)
dynamic_ip_mean,dynamic_ip_conf = conf_stats(dynamic_ip)
values = [fixed_noip_mean,fixed_ip_mean,dynamic_noip_mean, dynamic_ip_mean]
errs = [fixed_noip_conf,fixed_ip_conf,dynamic_noip_conf, dynamic_ip_conf]
y_pos = numpy.arange(len(values))
plt.barh(y_pos, values, xerr=errs, align='center', color=['r', 'b', 'r', 'b'], ecolor='black', alpha=0.7)
plt.yticks(y_pos, ["Fixed | no I.P.", "Fixed | I.P.", "Dynamic | no I.P.", "Dynamic | I.P."])
plt.savefig(output_file(filename))
plt.clf()
示例13: make_overview_plot
def make_overview_plot(filename, title, noip_arrs, ip_arrs):
plt.title("Inner parallelism - " + title)
plt.ylabel('Time (ms)', fontsize=12)
x = 0
barwidth = 0.5
bargroupspacing = 1.5
for z in zip(noip_arrs, ip_arrs):
noip,ip = z
noip_mean,noip_conf = conf_stats(noip)
ip_mean,ip_conf = conf_stats(ip)
b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7)
x += barwidth
b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7)
x += bargroupspacing
plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal')
fontP = FontProperties()
fontP.set_size('small')
plt.legend([b_noip, b_ip], \
('no inner parallelism', 'inner parallelism'), \
prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
plt.ylim([0,62000])
plt.savefig(output_file(filename))
plt.clf()
示例14: plot_precision_recall_n
def plot_precision_recall_n(y_true, y_scores, model_name):
'''
Takes the model, plots precision and recall curves
'''
precision_curve, recall_curve, pr_thresholds = precision_recall_curve(y_true, y_scores)
precision_curve = precision_curve[:-1]
recall_curve = recall_curve[:-1]
pct_above_per_thresh = []
number_scored = len(y_scores)
for value in pr_thresholds:
num_above_thresh = len(y_scores[y_scores >= value])
pct_above_thresh = num_above_thresh / float(number_scored)
pct_above_per_thresh.append(pct_above_thresh)
pct_above_per_thresh = np.array(pct_above_per_thresh)
plt.clf()
fig, ax1 = plt.subplots()
ax1.plot(pct_above_per_thresh, precision_curve, 'b')
ax1.set_xlabel('percent of population')
ax1.set_ylabel('precision', color='b')
ax2 = ax1.twinx()
ax2.plot(pct_above_per_thresh, recall_curve, 'r')
ax2.set_ylabel('recall', color='r')
name = model_name
plt.title(name)
plt.savefig("Eval/{}.png".format(name))
示例15: make_bar
def make_bar(
x,
y,
f_name,
title=None,
legend=None,
x_label=None,
y_label=None,
x_ticks=None,
y_ticks=None,
):
fig = plt.figure()
if title is not None:
plt.title(title, fontsize=16)
if x_label is not None:
plt.ylabel(x_label)
if y_label is not None:
plt.xlabel(y_label)
if x_ticks is not None:
plt.xticks(x, x_ticks)
if y_ticks is not None:
plt.yticks(y_ticks)
plt.bar(x, y, align="center")
if legend is not None:
plt.legend(legend)
plt.savefig(f_name)
plt.close(fig)