本文整理汇总了Python中matplotlib.pyplot.figtext函数的典型用法代码示例。如果您正苦于以下问题:Python figtext函数的具体用法?Python figtext怎么用?Python figtext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了figtext函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plot_onetimeseries_right
def plot_onetimeseries_right(fig,n,ThisOne,xarray,yarray,p):
if not p.has_key('ts_ax'):
ts_ax = fig.add_axes([p['ts_XAxOrg'],p['YAxOrg'],p['ts_XAxLen'],p['ts_YAxLen']])
ts_ax.hold(False)
ts_ax.yaxis.tick_right()
TextStr = ThisOne+'('+p['Units']+')'
txtXLoc = p['ts_XAxOrg']+0.01
txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
plt.figtext(txtXLoc,txtYLoc,TextStr,color='b',horizontalalignment='left')
else:
ts_ax = p['ts_ax'].twinx()
colour = 'r'
if p.has_key('ts_ax'): del p['ts_ax']
ts_ax.plot(xarray,yarray,'r-')
ts_ax.xaxis.set_major_locator(p['loc'])
ts_ax.xaxis.set_major_formatter(p['fmt'])
ts_ax.set_xlim(p['XAxMin'],p['XAxMax'])
ts_ax.set_ylim(p['RYAxMin'],p['RYAxMax'])
if n==0:
ts_ax.set_xlabel('Date',visible=True)
else:
ts_ax.set_xlabel('',visible=False)
TextStr = str(p['nNotM'])+' '+str(p['nMskd'])
txtXLoc = p['ts_XAxOrg']+p['ts_XAxLen']-0.01
txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
plt.figtext(txtXLoc,txtYLoc,TextStr,color='r',horizontalalignment='right')
if n > 0: plt.setp(ts_ax.get_xticklabels(),visible=False)
开发者ID:jberinge,项目名称:DINGO12,代码行数:27,代码来源:qcplot.py
示例2: MOorderplot
def MOorderplot(popul,path,picname=None,title=None):
x=[]; y1=[]; y2=[]; y3=[]; y4=[]; y5=[]; y6=[]; c=[]
for i,dude in enumerate(popul):
x.append(i)
y1.append(dude.no)
y2.append(dude.oldno)
y3.append(dude.ranks[0])
y4.append(dude.ranks[1])
y5.append(dude.score)
y6.append(dude.overall_rank)
c.append(dude.score)
f=plt.figure(figsize=(8,12)); a1=f.add_subplot(321); a2=f.add_subplot(322); a3=f.add_subplot(323); a4=f.add_subplot(324); a5=f.add_subplot(325); a6=f.add_subplot(326)
a1.scatter(x,y1,c=c,cmap=cm.gist_stern)
a2.scatter(x,y2,c=c,cmap=cm.gist_stern)
a3.scatter(x,y3,c=c,cmap=cm.gist_stern)
a4.scatter(x,y4,c=c,cmap=cm.gist_stern)
a5.scatter(x,y5,c=c,cmap=cm.gist_stern)
a6.scatter(x,y6,c=c,cmap=cm.gist_stern)
a1.set_xlabel('place in population'); a1.set_ylabel('dude.no')
a2.set_xlabel('place in population'); a2.set_ylabel('dude.oldno')
a3.set_xlabel('place in population'); a3.set_ylabel('dude.ranks[0]')
a4.set_xlabel('place in population'); a4.set_ylabel('dude.ranks[1]')
a5.set_xlabel('place in population'); a5.set_ylabel('dude.score')
a6.set_xlabel('place in population'); a6.set_ylabel('dude.overall_rank')
if title is not None: plt.figtext(0.5, 0.98,title,va='top',ha='center', color='black', weight='bold', size='large')
if picname is not None:
plt.savefig(join(path,picname))
else:
plt.savefig(join(path,'orderplot_c'+str(popul.ncase)+'_sc'+str(popul.subcase).zfill(3)+'_g'+str(popul.gg)+'.png'))
plt.close()
开发者ID:antiface,项目名称:peabox,代码行数:30,代码来源:peabox_plotting.py
示例3: plot_1d
def plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = False, t0 = 0, **kwargs):
""" Creates a 1D scatter/line plot:
Usage: plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = [False|True], t0 = 0)
Arguments:
xdata, ydata: self-explanatory
color: color to be used to plot data
x_axis, y_axis: strings to be used for the axis label
system: descriptor for the system that produced the data
analysis: descriptor for the analysis that produced the data
average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data # THERE IS A BUG IF average=True; must read in yunits for this function to work at the moment.
t0: index to begin averaging from; Default is 0
kwargs:
xunits, yunits: string with correct math text describing the units for the x/y data
x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
plt_title: string to be added as the plot title
draw_line: int value that determines the line style to be drawn; giving myself space to add more line styles if I decide I need them
"""
# INITIATING THE PLOT...
plt.plot(xdata, ydata, '%s' %(color))
# READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
for name, value in kwargs.items():
if name == 'xunits':
x_units = value
x_axis = '%s (%s)' %(x_axis, value)
elif name == 'yunits':
y_units = value
y_axis = '%s (%s)' %(y_axis, value)
elif name == 'x_lim':
plt.xlim(value)
elif name == 'y_lim':
plt.ylim(value)
elif name == 'plt_title':
plt.title(r'%s' %(value), size='14')
elif name == 'draw_line':
draw_line = value
if draw_line == 1:
plt.plot([0,max(ydata)],[0,max(ydata)],'r-',linewidth=2)
else:
print 'draw_line = %s has not been defined in plotting_functions script' %(line_value)
plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--')
plt.xlabel(r'%s' %(x_axis), size=12)
plt.ylabel(r'%s' %(y_axis), size=12)
# CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
if average != False:
avg = np.sum(ydata[t0:])/len(ydata[t0:])
SD = stdev(ydata[t0:])
SDOM = SD/sqrt(len(ydata[t0:]))
plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')
plt.figtext(0.680, 0.780, '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %(analysis, avg, SDOM, y_units, SD, y_units), bbox=dict(boxstyle='square', ec='r', fc='w'), fontsize=12)
plt.savefig('%s.%s.plot1d.png' %(system,analysis),dpi=300)
plt.close()
开发者ID:rbdavid,项目名称:Distance_matrix,代码行数:60,代码来源:plotting_functions.py
示例4: plot_multiline
def plot_multiline(data_list, legend_list, picture_title, picture_save_path, text=None):
""" Draw data series info """
# plot file and save picture
fig = plt.figure(figsize=(15, 6))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
if text is not None:
plt.figtext(0.01, 0.01, text, horizontalalignment='left')
date_series = data_list[0].index
color_list = ['r-', 'b-', 'y-', 'g-']
for i, data_series in enumerate(data_list):
# get data series info
plt.plot(date_series, data_series, color_list[i], label=legend_list[i])
min_date = date_series[0]
max_date = date_series[-1]
plt.gca().set_xlim(min_date, max_date)
plt.legend(loc=0)
fig.autofmt_xdate()
fig.suptitle(picture_title)
# print dir(fig)
fig.savefig(picture_save_path)
plt.close()
开发者ID:WarnWang,项目名称:QuestionFromProfWang,代码行数:29,代码来源:util_function_class.py
示例5: write
def write(self):
self.writePreHook()
for cut in self.contourData.filteredCombinedData:
# Add cut to the output filename
(outputFilename, ext) = os.path.splitext(self.outputFilename)
outputFilename = "{0}_{1}_{2:.0f}{3}".format(outputFilename, cut.key, cut.value, ext)
plt.ioff()
plt.figure(figsize=(8,6))
#plt.yscale('log')
plt.ylim([0,1.0])
plt.figtext(0.05, 0.96, 'Cut: {0} = {1:.0f}'.format(cut.key, cut.value), color='grey', size='small')
plt.figtext(0.05, 0.93, 'Plot written at {:%d/%m/%Y %H:%M}'.format(datetime.datetime.now()), color='grey', size='small')
for f in self.contourData.contributingRegionsFiltered[cut]:
data = self.contourData.filteredData[f][cut]
label = filterLabel(f, self.gridConfig)
if not cut.isSimple():
plt.xticks( np.arange(len(data)), ["%d_%d" % (x[self.gridConfig.x], x[self.gridConfig.y]) for x in data.values()])
xLabel = "Grid point"
else:
var = self.gridConfig.x
if cut.key == var:
var = self.gridConfig.y
xLabel = var
plt.xticks( np.arange(len(data)), ["%d" % (x[var]) for x in data.values()])
print [x[self.contourData.combineOn] for x in data.values()]
plt.plot( [x[self.contourData.combineOn] for x in data.values()], label=label )
plt.plot( [0.05 for x in data.values()], color='r', linestyle='--', linewidth=2)
开发者ID:lawrenceleejr,项目名称:ZeroLeptonAnalysis,代码行数:32,代码来源:optimisationplot.py
示例6: plot_tiegcm
def plot_tiegcm(time, lat, lon, den, temp, ht, pres, image_name):
"""Plot density, temperature, and geopotential height
for all latitudes and longitudes at relevant time"""
y_values = [-90, -45, 0, 45, 90]
x_values = [-180, -135, -90, -45, 0, 45, 90, 135, 180]
fig = plt.figure()
# fig.subplots_adjust(left = 0.25, right = 0.7, bottom = 0.07, top = 0.9, wspace = 0.2, hspace = 0.08)
sub_den = fig.add_subplot(3, 1, 1)
plot_settings(sub_den, den*1e12, lon, lat,
y_values, x_values = [],
ylabel = "", xlabel = "",
title = 'Density',
ctitle = r"x 10$^{-12}$ kgm$^{-3}$ ",
minmax = [2., 4.])
pres = format(pres, '.2e')
plt.title('{} at {} Pa'.format(time, pres), fontsize = 11)
sub_temp = fig.add_subplot(3, 1, 2)
plot_settings(sub_temp, temp, lon, lat,
y_values, x_values = [],
ylabel = 'Latitude [$^\circ$]', xlabel = "",
title = 'Temperature',
ctitle = "Kelvin",
minmax = [750., 1250.])
sub_ht = fig.add_subplot(3, 1, 3)
plot_settings(sub_ht, ht/100000., lon, lat,
y_values, x_values,
ylabel = " ", xlabel = 'Longitude [$^\circ$]',
title = 'Geopotential Height',
ctitle = "km",
minmax = [350., 450.])
plt.figtext(.6, .032, r'$\copyright$ Crown Copyright. Source: Met Office', size = 8)
plt.tight_layout()
# insert_logo()
save_to_web(fig, time, image_name)
开发者ID:sophiemurray,项目名称:tiegcm,代码行数:34,代码来源:tie_plot.py
示例7: plotEvolution
def plotEvolution(self, var, name, name_long="new plot", figlabel="Resolution", ylabel="", loc="", reference=False):
"""
Plots evolution in time of the given variable.
"""
plt.clf()
var = np.array(var)
if var.ndim == 1: # in case a single set of data is provided
var = [var]
ls = ["-.", "--", "-"]
kwargs = {}
if "bw" in self.file_name:
kwargs["color"] = "k"
for i in range(len(self.t)):
plt.plot(self.t[i], var[i], label="{0} {1}".format(figlabel, i + 1), ls=ls[i], **kwargs)
plt.title(self.title.format(name_long))
plt.xlabel(self.xlabel)
plt.ylabel(ylabel)
if self.info:
plt.figtext(self.text_pos[0], self.text_pos[1], self.info)
plt.xlim(np.round(np.min(self.t[0])), np.round(np.max(self.t[0])))
if reference:
self.plotReference()
plt.legend(loc=loc or self.loc)
for e in self.ext:
plt.savefig(os.path.join(self.out_dir, self.file_name.format(name=name, ext=e)))
开发者ID:pawelaw,项目名称:phd,代码行数:26,代码来源:postprocess.py
示例8: i2pcontrol_stats
def i2pcontrol_stats(conn, output=''):
things=[
{'stat':'activepeers','xlab':'time','ylab':'total',},
{'stat':'tunnelsparticipating','xlab':'time','ylab':'total',},
{'stat':'decryptFail','xlab':'time','ylab':'total',},
{'stat':'failedLookupRate','xlab':'time','ylab':'total',},
{'stat':'streamtrend','xlab':'time','ylab':'total',},
{'stat':'windowSizeAtCongestion','xlab':'time','ylab':'total',},
#{'stat':'','xlab':'','ylab':'',}, # Template to add more.
]
tokens = query_db(conn, 'select owner,token from submitters;')
for thing in things:
combined=[]
dfs=[]
for token in tokens:
q = 'select datetime(cast(((submitted)/({0})) as int)*{0}, "unixepoch") as sh, {1} from speeds where submitter="{2}" group by sh order by sh desc;'.format(interval, thing['stat'], token[1])
df = pd.read_sql_query(q, conn)
# unix -> human
df['sh'] = pd.to_datetime(df['sh'], unit='s')
dfs.append(df)
# Reverse so it's put in left to right
combined = reduce(lambda left,right: pd.merge(left,right,on='sh',how='outer'), dfs)
combined.columns=['time'] + [i[0] for i in tokens]
combined = combined.set_index('time')
combined.head(num_intervals).plot(marker='o')
plt.figtext(.1,.03,'{}\n{} UTC'.format(site,generation_time))
plt.title(thing['stat'])
plt.xlabel(thing['xlab'])
plt.ylabel(thing['ylab'])
plt.savefig('{}/{}.png'.format(output, thing['stat']))
plt.close()
开发者ID:Artogn,项目名称:i2spy,代码行数:34,代码来源:viewer.py
示例9: DBLR_f
def DBLR_f(self):
global a
#if (self.graph_sw.get()==True):
b=a
a=a+1
#else:
# b=0
aux=self.base_path.get()
# path=''.join([aux,str(self.meas.get()),'.txt'])
# g=pd.read_csv(path)
f=read_panel_hdf5(aux, self.point.get(), self.meas.get())
f=4096-f
recons,energia = DB.BLR( signal_daq=f.flatten().astype(float),
coef=self.coef.get(),
n_sigma=self.n_sigma.get(),
NOISE_ADC=self.noise.get(),
thr1=self.thr1.get(),
thr2=self.thr2.get(),
thr3=self.thr3.get(),
plot=False)
plt.figure(a)
plt.plot(recons)
plt.figtext(0.2,0.75, ('ENERGY = %0.2f ' % (energia)))
plt.show()
开发者ID:jjgomezcadenas,项目名称:IC,代码行数:28,代码来源:DBLR_GUI.py
示例10: execute
def execute(model, data, savepath, *args, **kwargs):
descriptors = ['Cu (At%)', 'Ni (At%)', 'Mn (At%)', 'P (At%)', 'Si (At%)', 'C (At%)', 'Temp (C)', 'log(fluence)',
'log(flux)']
xlist = np.asarray(data.get_data(descriptors))
model = model
model.fit(data.get_x_data(), np.array(data.get_y_data()).ravel())
error = model.predict(data.get_x_data()) - np.array(data.get_y_data()).ravel()
for x in range(len(descriptors)):
plt.scatter(xlist[:, x], error, color='black', s=10)
xlim = plt.gca().get_xlim()
plt.plot(xlim, (20, 20), ls="--", c=".3")
plt.plot(xlim, (0, 0), ls="--", c=".3")
plt.plot(xlim, (-20, -20), ls="--", c=".3")
m, b = np.polyfit(np.reshape(xlist[:, x], len(xlist[:, x])), np.reshape(error, len(error)),1) # line of best fit
matplotlib.rcParams.update({'font.size': 15})
plt.plot(xlist[:, x], m * xlist[:, x] + b, color='red')
plt.figtext(.15, .83, 'y = ' + "{0:.6f}".format(m) + 'x + ' + "{0:.5f}".format(b), fontsize=14)
plt.title('Error vs. {}'.format(descriptors[x]))
plt.xlabel(descriptors[x])
plt.ylabel('Predicted - Actual (Mpa)')
plt.savefig(savepath.format(plt.gca().get_title()), dpi=200, bbox_inches='tight')
plt.close()
开发者ID:UWMad-Informatics,项目名称:standardized,代码行数:26,代码来源:ErrorBias.py
示例11: pie_graph
def pie_graph(conn, query, output, title='', lower=0, log=False):
labels = []
sizes = []
res = query_db(conn, query)
# Sort so the graph doesn't look like complete shit.
res = sorted(res, key=lambda tup: tup[1])
for row in res:
if row[1] > lower:
labels.append(row[0])
if log:
sizes.append(math.log(row[1]))
else:
sizes.append(row[1])
# Normalize.
norm = [float(i)/sum(sizes) for i in sizes]
plt.pie(norm,
labels=labels,
shadow=True,
startangle=90,
)
plt.figtext(.1,.03,'{}\n{} UTC'.format(site,generation_time))
plt.axis('equal')
plt.legend()
plt.title(title)
plt.savefig(output)
plt.close()
开发者ID:Artogn,项目名称:i2spy,代码行数:28,代码来源:viewer.py
示例12: show_spider
def show_spider(p):
L = Logging('log')
data = L.get_stacked_bar_data('Template', p, 'spider')
N = 12
theta = radar_factory(N, frame='polygon')
spoke_labels = data.pop('column names')
fig = plt.figure(figsize=(7, 7))
fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
colors = ['r', 'g', 'b', 'm', 'y']
# Plot the four cases from the example data on separate axes
for n, title in enumerate(data.keys()):
ax = fig.add_subplot(1, 1, n + 1, projection='radar')
# plt.rgrids([0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
horizontalalignment='center', verticalalignment='center')
for d, color in zip(data[title], colors):
ax.plot(theta, d, color=color)
ax.fill(theta, d, facecolor=color, alpha=0.25)
ax.set_varlabels(spoke_labels)
# add legend relative to top-left plot
plt.subplot(1, 1, 1)
labels = ('Losers', 'Winners')
legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize='small')
plt.figtext(0.5, 0.965, 'Winner vs Losers',
ha='center', color='black', weight='bold', size='large')
plt.show()
开发者ID:NoCredits,项目名称:Poker,代码行数:33,代码来源:Charts.py
示例13: plot_results
def plot_results(datas, factor=None, algo='FFT'):
xlabel = r'Array Size (2^x)'
ylabel = 'Speed (GFLOPs)'
backends = ['numpy', 'numpy+mkl']
plt.clf()
fig1, ax1 = plt.subplots()
plt.figtext(0.90, 0.94, "Note: higher is better", va='top', ha='right')
w, h = fig1.get_size_inches()
fig1.set_size_inches(w*1.5, h)
ax1.get_xaxis().set_major_formatter(ticker.ScalarFormatter())
ax1.get_xaxis().set_minor_locator(ticker.NullLocator())
ax1.set_xticks(datas[0][:,0])
ax1.grid(color="lightgrey", linestyle="--", linewidth=1, alpha=0.5)
if factor:
ax1.set_xticklabels([str(int(x)) for x in datas[0][:,0]/factor])
plt.xlabel(xlabel, fontsize=16)
plt.ylabel(ylabel, fontsize=16)
plt.xlim(datas[0][0,0]*.9, datas[0][-1,0]*1.025)
plt.suptitle("%s Performance" % ("FFT"), fontsize=28)
for backend, data in zip(backends, datas):
N = data[:, 0]
plt.plot(N, data[:, 1], 'o-', linewidth=2, markersize=5, label=backend)
plt.legend(loc='upper left', fontsize=18)
plt.savefig(algo + '.png')
开发者ID:Nie-yingchun,项目名称:mkl-optimizations-benchmarks,代码行数:27,代码来源:benchFFT.py
示例14: plotta
def plotta(im,xx,yy,ext):
#make plot
f = ap.FITSFigure(im,figure=fig,subplot=[xx,yy-dy,dx,dy])
f.show_colorscale(cmap = 'hot', vmin = -1.245E-02, vmax = 2.405E-02 )
f.recenter(ra, dec, re_cen)
#if ext == 'E':
f.show_ellipses(ra, dec, a/60.0, b/60.0, angle=pa-90, edgecolor='grey', lw=2)
#if ext == 'P':
#f.show_markers(ra, dec, c='grey',marker='x')
#f.add_scalebar(1.0/60.0)
f.scalebar.set_label('1 arcmin')
#f.scalebar.set_color('white')
#f.show_grid()
#f.set_tick_labels_format(xformat='hh:mm:ss',yformat='dd:mm:ss')
#f.show_markers(ra, dec, c='red',marker='x')
#f.add_beam(major=beam, minor=beam,angle=0.0)
f.show_beam(major=beam, minor=beam,angle=0.0,fc='white')
f.axis_labels.hide()
f.tick_labels.hide()
# add text
plt.figtext(xx+0.012 , yy-dy+0.14, name, size=20, weight="bold", color='white')
开发者ID:9217392354A,项目名称:astro-scripts,代码行数:28,代码来源:full_page_figures_detections.py
示例15: beaut
def beaut(fig, axes):
for row_i, axes_row in enumerate(axes):
for col_i, ax in enumerate(axes_row):
ax.set_xticks([])
ax.set_yticks([])
if col_i == 0:
ax.set_ylabel(str(row_i))
if row_i == 9:
ax.set_xlabel(str(col_i))
plt.figtext(
0.5,
0,
"public goods effect threshold",
figure=fig,
fontsize=17,
horizontalalignment='center',
verticalalignment='top',
)
plt.figtext(
0,
0.5,
"quorum sensing threshold",
figure=fig,
fontsize=17,
horizontalalignment='right',
verticalalignment='center',
rotation=90,
)
fig.tight_layout()
开发者ID:yuvallanger-tau,项目名称:strife-article,代码行数:35,代码来源:strife.py
示例16: shots4time
def shots4time(player='Noah', team='CHI',
s_date='20091001', f_date='20151231', path='D:\Gal\Work\Results'):
''' '''
actions_1, played_games_1 = actions_raster(players=[player], team=team,
s_date=s_date, f_date=f_date, path=path, action=c.Shot)
actions_2, played_games_2 = time_raster(player, team, s_date, f_date, path)
actions_3, played_games_3 = actions_raster(players=[player], team=team,
s_date=s_date, f_date=f_date, path=path, action=c.FreeThrow)
plt.hold(1)
# plt.title(player+','+team)
# plt.plot(actions_1, played_games_1, 'b.')
# plt.plot(actions_3, played_games_3, 'm.')
plt.figure(1)
plt.plot(actions_histogram(actions_1), 'b')
plt.plot(actions_histogram(actions_2), 'r')
plt.plot(actions_histogram(actions_3), 'm')
plt.figure(2)
plt.title(player+','+team)
plt.figtext(0, 0.5, 'blue - shots \n'+'red - presentce on court\n'+'magenta - freethrows')
plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_1), 3)), 'b')
plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_2), 3)), 'r')
plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_3), 3)), 'm')
plt.xlabel('Time (in half minutes)')
plt.ylabel('Points')
plt.grid(axis='x')
plt.xticks(np.arange(1, 5)*c.Q_LEN/30)
plt.show()
开发者ID:DkChi,项目名称:NBA-Project,代码行数:30,代码来源:research_functions_NBA.py
示例17: save_fig
def save_fig(self, poly=None, directory="/tmp/plots",
overwrite=False, labels=None, extension=".png"):
"""Save the pass as a figure. Filename is automatically generated.
"""
logger.debug("Save fig " + str(self))
rise = self.risetime.strftime("%Y%m%d%H%M%S")
fall = self.falltime.strftime("%Y%m%d%H%M%S")
filename = os.path.join(directory,
(rise + self.satellite.replace(" ", "_") + fall + extension))
self.fig = filename
if not overwrite and os.path.exists(filename):
return filename
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.clf()
with Mapper() as mapper:
mapper.nightshade(self.uptime, alpha=0.2)
self.draw(mapper, "-r")
if poly is not None:
poly.draw(mapper, "-b")
plt.title(str(self))
for label in labels or []:
plt.figtext(*label[0], **label[1])
plt.savefig(filename)
return filename
开发者ID:alexmaul,项目名称:pytroll-schedule,代码行数:28,代码来源:satpass.py
示例18: plot_graph
def plot_graph(data_frame, data_frame_features):
data_frame_features.remove('irisClass')
grouped_data_frame = data_frame.groupby(data_frame['irisClass']).apply(
lambda tdf: pd.Series(dict([[vv, tdf[vv].tolist()] for vv in tdf if
vv not in ['irisClass']])))
flower_list = set(data_frame['irisClass'])
for feature in data_frame_features:
data = []
fig, box_plotter = plt.subplots(figsize=(10, 6))
box_plotter.yaxis.grid(True, linestyle='-', which='major',
color='lightgrey',
alpha=0.5)
# Hide these grid behind plot objects
box_plotter.set_axisbelow(True)
box_plotter.set_xlabel('Distribution of flowers')
box_plotter.set_ylabel('Length of features')
box_plotter.set_title('Comparison of %s across flowers' % (feature))
for flower in flower_list:
data.append(grouped_data_frame[feature][flower])
plt.figtext(0.8, 0.9,
'1 --> Iris-Versicolor\n2--> Iris-Virginica\n3--> '
'Iris-Setosa',
backgroundcolor='white', color='black', weight='roman',
size='medium')
box_plotter.boxplot(data)
plt.show()
开发者ID:narayana1043,项目名称:course_works,代码行数:26,代码来源:q1_answer.py
示例19: plot_radar
def plot_radar(gene2plot, tissue, path):
'''
Plot radar plot
:param data:
:param path:
:return:
'''
data = gene2plot
#[0.00364299,0.0582878,0.04189435,0.13661202,0.10928962,0.14754098,0.00728597,0.0582878,0.40801457,0.3]
spoke_labels = tissue
#['lung', 'bone', 'blood', 'epithelial', 'progenitor', 'nervous', 'endocrine', 'epidermal', 'immune','liver']
N = len(data)
theta = radar_factory(N, frame='polygon')
plt.rcParams['font.size'] = 10
fig = plt.figure(figsize=(6, 6))
fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
ax = fig.add_subplot(1, 1, 1, projection='radar')
#plt.rgrids([0.1, 0.2, 0.3, 0.4])
#ax.set_title('Fraction of gene', weight='bold', fontsize=15, position=(0.5, 1.1),
# horizontalalignment='center', verticalalignment='center')
ax.plot(theta, data, color='r', lw=1)
ax.fill(theta, data, facecolor='r', alpha=0.25)
ax.set_varlabels(spoke_labels)
plt.figtext(0.5, 0.965, 'Gene enrichment fraction for (tissue)* types',
ha='center', color='black', weight='bold', fontsize=15)
plt.savefig(os.path.join(path, 'GCAM_redar.svg'))
plt.clf()
plt.close()
开发者ID:peeyushsahu,项目名称:analysisTools,代码行数:30,代码来源:plots.py
示例20: _get_3d_plot
def _get_3d_plot(self, label_stable=True):
"""
Shows the plot using pylab. Usually I won"t do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way.
"""
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.font_manager import FontProperties
fig = plt.figure()
ax = p3.Axes3D(fig)
font = FontProperties()
font.set_weight("bold")
font.set_size(20)
(lines, labels, unstable) = self.pd_plot_data
count = 1
newlabels = list()
for x, y, z in lines:
ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10)
for coords in sorted(labels.keys()):
entry = labels[coords]
label = entry.name
if label_stable:
if len(entry.composition.elements) == 1:
ax.text(coords[0], coords[1], coords[2], label)
else:
ax.text(coords[0], coords[1], coords[2], str(count))
newlabels.append("{} : {}".format(count, latexify(label)))
count += 1
plt.figtext(0.01, 0.01, "\n".join(newlabels))
ax.axis("off")
return plt
开发者ID:qimin,项目名称:pymatgen,代码行数:33,代码来源:plotter.py
注:本文中的matplotlib.pyplot.figtext函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论