本文整理汇总了Python中matplotlib.pyplot.clf函数的典型用法代码示例。如果您正苦于以下问题:Python clf函数的具体用法?Python clf怎么用?Python clf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_by_groups
def plot_by_groups(df, plot_dir, af_key, config):
"""Plot allele frequencies of grouped/paired samples.
"""
out_file = os.path.join(plot_dir, "cohort-group-af-comparison.pdf")
df["sample_label"] = df.apply(lambda row: "%s\n%s" % (row["group_class"], row["sample"]), axis=1)
sns.despine()
sns.set(style="white")
with PdfPages(out_file) as pdf_out:
for (cohort, group), cur_df in df.groupby(["cohort", "group"]):
labels = sorted(list(cur_df["sample_label"].unique()))
labels.reverse()
cur_df["sample_label"].categories = labels
g = sns.violinplot(x=af_key, y="sample_label", data=cur_df, inner=None, bw=.1)
#sns.swarmplot(x=af_key, y="sample_label", data=cur_df, color="w", alpha=.5)
try:
group = int(group)
except ValueError:
pass
g.set_title("%s: %s" % (cohort, group))
g = _af_violinplot_shared(g)
pdf_out.savefig(g.figure)
if config and (cohort, group) in config.group_detailed:
out_dir = utils.safe_makedir(os.path.join(plot_dir, "detailed"))
out_file = os.path.join(out_dir, "group-%s-%s.png" % (cohort, group))
g.figure.savefig(out_file)
plt.clf()
return out_file
示例2: run_test
def run_test(fld, seeds, plot2d=True, plot3d=True, add_title="",
view_kwargs=None, show=False, scatter_mpl=False, mesh_mvi=True):
interpolated_fld = viscid.interp_trilin(fld, seeds)
seed_name = seeds.__class__.__name__
if add_title:
seed_name += " " + add_title
try:
if not plot2d:
raise ImportError
from viscid.plot import vpyplot as vlt
from matplotlib import pyplot as plt
plt.clf()
# plt.plot(seeds.get_points()[2, :], fld)
mpl_plot_kwargs = dict()
if interpolated_fld.is_spherical():
mpl_plot_kwargs['hemisphere'] = 'north'
vlt.plot(interpolated_fld, **mpl_plot_kwargs)
plt.title(seed_name)
plt.savefig(next_plot_fname(__file__, series='2d'))
if show:
plt.show()
if scatter_mpl:
plt.clf()
vlt.plot2d_line(seeds.get_points(), fld, symdir='z', marker='o')
plt.savefig(next_plot_fname(__file__, series='2d'))
if show:
plt.show()
except ImportError:
pass
try:
if not plot3d:
raise ImportError
from viscid.plot import vlab
_ = get_mvi_fig(offscreen=not show)
try:
if mesh_mvi:
mesh = vlab.mesh_from_seeds(seeds, scalars=interpolated_fld)
mesh.actor.property.backface_culling = True
except RuntimeError:
pass
pts = seeds.get_points()
p = vlab.points3d(pts[0], pts[1], pts[2], interpolated_fld.flat_data,
scale_mode='none', scale_factor=0.02)
vlab.axes(p)
vlab.title(seed_name)
if view_kwargs:
vlab.view(**view_kwargs)
vlab.savefig(next_plot_fname(__file__, series='3d'))
if show:
vlab.show(stop=True)
except ImportError:
pass
示例3: 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))
示例4: LinRegTest
def LinRegTest(XTrain, YTrain, close, filename):
'''
Using RandomForest learner to predict how much the price will change in 5 days
@filename: the file's true name is ML4T-filename
@XTrain: the train data for feature
@YTrain: the train data for actual price after 5 days
@close: the actual close price of Test data set
@k: the number of trees in the forest
'''
XTest, YTest = TestGenerator(close)
#plot thge feature
plt.clf()
fig = plt.figure()
fig.suptitle('The value of features')
plt.plot(range(100), XTest[0:100, 0], 'b', label = 'One day price change')
plt.plot(range(100), XTest[0:100, 1], 'r', label = 'difference between two day price change')
plt.legend(loc = 4)
plt.ylabel('Price')
filename4 = 'feature' + filename + '.pdf'
fig.savefig(filename4, format = 'pdf')
LRL = LinRegLearner()
cof = LRL.addEvidence(XTrain, YTrain)
YLearn = LRL.query(XTest, cof)
return YLearn
示例5: 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))
示例6: 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()
示例7: 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')
示例8: display_graph_by_specific_mac
def display_graph_by_specific_mac(self, mac_address):
G = nx.Graph()
count = 0
edges = set()
edges_list = []
for pkt in self.pcap_file:
src = pkt[Dot11].addr1
dst = pkt[Dot11].addr2
if mac_address in [src, dst]:
edges_list.append((src, dst))
edges.add(src)
edges.add(dst)
plt.clf()
plt.suptitle('Communicating with ' + str(mac_address), fontsize=14, fontweight='bold')
plt.title("\n Number of Communicating Users: " + str(int(len(edges))))
plt.rcParams.update({'font.size': 10})
G.add_edges_from(edges_list)
nx.draw(G, with_labels=True, node_color=MY_COLORS)
plt.show()
示例9: graph_by_sender
def graph_by_sender(self):
mac_adresses = {} # new dictionary
for pkt in self.pcap_file:
mac_adresses.update({pkt[Dot11].addr2: 0})
for pkt in self.pcap_file:
mac_adresses[pkt[Dot11].addr2] += 1
MA = []
for ma in mac_adresses:
MA.append(mac_adresses[ma])
plt.clf()
plt.suptitle('Number of packets of every sender', fontsize=14, fontweight='bold')
plt.bar(range(len(mac_adresses)), sorted(MA), align='center', color=MY_COLORS)
plt.xticks(range(len(mac_adresses)), sorted(mac_adresses.keys()))
plt.rcParams.update({'font.size': 10})
plt.xlabel('Senders mac addresses')
plt.ylabel('Number of packets')
# Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='k')
ax.tick_params(axis='y', colors='r')
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
plt.show()
示例10: display_channel_efficiency
def display_channel_efficiency(self):
size = 0
start_time = self.pcap_file[0].time
end_time = self.pcap_file[len(self.pcap_file) - 1].time
duration = (end_time - start_time)/1000
for i in range(len(self.pcap_file) - 1):
size += len(self.pcap_file[i])
ans = (((size * 8) / duration) / BW_STANDARD_WIFI) * 100
ans = float("%.2f" % ans)
labels = ['utilized', 'unutilized']
sizes = [ans, 100.0 - ans]
colors = ['g', 'r']
# Make a pie graph
plt.clf()
plt.figure(num=1, figsize=(8, 6))
plt.axes(aspect=1)
plt.suptitle('Channel efficiency', fontsize=14, fontweight='bold')
plt.title("Bits/s: " + str(float("%.2f" % ((size*8)/duration))),fontsize = 12)
plt.rcParams.update({'font.size': 17})
plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2)
plt.show()
示例11: display_PER
def display_PER(self):
number_of_pkts = len(self.pcap_file)
retransmission_pkts = 0
for pkt in self.pcap_file:
if (pkt[Dot11].FCfield & 0x8) != 0:
retransmission_pkts += 1
ans = (retransmission_pkts / number_of_pkts)*100
ans = float("%.2f" % ans)
labels = ['Standard packets', 'Retransmitted packets']
sizes = [100.0 - ans,ans]
colors = ['g', 'firebrick']
# Make a pie graph
plt.clf()
plt.figure(num=1, figsize=(8, 6))
plt.axes(aspect=1)
plt.suptitle('Retransmitted packet', fontsize=14, fontweight='bold')
plt.rcParams.update({'font.size': 13})
plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2)
plt.show()
示例12: display_graph
def display_graph(self):
G = nx.Graph()
count = 0
edges = set()
edges_list = []
for pkt in self.pcap_file:
if pkt.haslayer(Dot11Elt):
src = pkt[Dot11].addr1
dst = pkt[Dot11].addr2
edges_list.append((src, dst))
edges.add(src)
edges.add(dst)
plt.clf()
filepath = os.path.splitext(self.path)[0]
filename = basename(filepath)
plt.suptitle('Connection Map of: '+ str(filename), fontsize=14, fontweight='bold')
plt.title("\n Number of Users: " + str(int(len(edges))))
plt.rcParams.update({'font.size': 10})
G.add_edges_from(edges_list)
nx.draw(G, with_labels=True, node_color=MY_COLORS)
plt.show()
示例13: ensemble_pca
def ensemble_pca(self, ref_ensemble=None, ref_first=True):
data = prepare_pca_input(self._cgs)
pca = PCA(n_components=2)
if ref_ensemble:
ref_data = prepare_pca_input(ref_ensemble)
if ref_first:
pca.fit(ref_data)
if not ref_ensemble or not ref_first:
pca.fit(data)
reduced_data = pca.transform(data)
if ref_ensemble:
reduced_ref = pca.transform(ref_data)
plt.scatter(reduced_ref[:, 0], reduced_ref[:, 1],
color="green", label="background")
plt.scatter(reduced_data[:, 0], reduced_data[:,
1], color="blue", label="sampling")
if self._reference_cg:
data_true = prepare_pca_input([self._reference_cg])
reduced_true = pca.transform(data_true)
plt.scatter(reduced_true[:, 0], reduced_true[:,
1], color="red", label="reference")
plt.xlabel("First principal component")
plt.ylabel("Second principal component")
figname = "pca_{}_rf{}.svg".format(self._cgs[0].name, ref_first)
plt.savefig(figname)
log.info("Figure {} created".format(figname))
plt.clf()
plt.close()
示例14: view_delta_rmsd_vs_steps
def view_delta_rmsd_vs_steps(self):
self._calculate_complete_rmsd_matrix()
fig, axes = plt.subplots(2)
a_rmsd = np_nans(len(self._cg_sequence) // 2)
min_rmsd = np_nans(len(self._cg_sequence) // 2)
max_rmsd = np_nans(len(self._cg_sequence) // 2)
for d in range(len(a_rmsd)):
l = [self._rmsd[self._cg_sequence[i], self._cg_sequence[i + d]]
for i in range(len(self._cg_sequence) - d)]
a_rmsd[d] = sum(l) / len(l)
min_rmsd[d] = min(l)
max_rmsd[d] = max(l)
for ax in axes:
ax.set_xlabel("Steps apart")
ax.set_ylabel("Average RMSD")
ax.plot(list(range(len(a_rmsd))), a_rmsd, label="Average RMSD")
ax.plot(list(range(len(min_rmsd))), min_rmsd, label="Minimal RMSD")
ax.plot(list(range(len(max_rmsd))), max_rmsd, label="Maximal RMSD")
ax.plot([0, len(max_rmsd)], [np.max(self._rmsd), np.max(
self._rmsd)], "-.", label="Maximal RMSD in whole simulation")
ax.plot([0, len(max_rmsd)], [np.mean(self._rmsd), np.mean(
self._rmsd)], "-.", label="Average RMSD in whole simulation")
ax.legend(prop={'size': 6})
axes[1].set_xlim([0, 50])
plt.savefig("rmsd_steps_apart_{}.svg".format(self._cgs[0].name))
plt.clf()
plt.close()
示例15: disc_norm
def disc_norm():
x = np.linspace(-3,3,100)
y = st.norm.pdf(x,0,1)
fig, ax = plt.subplots()
fig.canvas.draw()
ax.plot(x,y)
fill1_x = np.linspace(-2,-1.5,100)
fill1_y = st.norm.pdf(fill1_x,0,1)
fill2_x = np.linspace(-1.5,-1,100)
fill2_y = st.norm.pdf(fill2_x,0,1)
ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
for label in ax.get_yticklabels():
label.set_visible(False)
for tick in ax.get_xticklines():
tick.set_visible(False)
for tick in ax.get_yticklines():
tick.set_visible(False)
plt.rc("font", size = 16)
plt.xticks([-2,-1.5,-1])
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = r"$v_k$"
labels[1] = r"$\varepsilon_k$"
labels[2] = r"$v_{k+1}$"
ax.set_xticklabels(labels)
plt.ylim([0, .45])
plt.savefig('discnorm.pdf')
plt.clf()