本文整理汇总了Python中pylab.plt.figure函数的典型用法代码示例。如果您正苦于以下问题:Python figure函数的具体用法?Python figure怎么用?Python figure使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了figure函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: link_level_bars
def link_level_bars(levels, usages, quantiles, scheme, direction, color, nnames, lnames, admat=None):
"""
Bar plots of nodes' link usage of links at different levels.
"""
if not admat:
admat = np.genfromtxt('./settings/eadmat.txt')
if color == 'solar':
cmap = Oranges_cmap
elif color == 'wind':
cmap = Blues_cmap
elif color == 'backup':
cmap = 'Greys'
nodes, links = usages.shape
usageLevels = np.zeros((nodes, levels))
usageLevelsNorm = np.zeros((nodes, levels))
for node in range(nodes):
nl = neighbor_levels(node, levels, admat)
for lvl in range(levels):
ll = link_level(nl, lvl, nnames, lnames)
ll = np.array(ll, dtype='int')
usageSum = sum(usages[node, ll])
linkSum = sum(quantiles[ll])
usageLevels[node, lvl] = usageSum / linkSum
if lvl == 0:
usageLevelsNorm[node, lvl] = usageSum
else:
usageLevelsNorm[node, lvl] = usageSum / usageLevelsNorm[node, 0]
usageLevelsNorm[:, 0] = 1
# plot all nodes
usages = usageLevels.transpose()
plt.figure(figsize=(11, 3))
ax = plt.subplot()
plt.pcolormesh(usages[:, loadOrder], cmap=cmap)
plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11)
ax.set_yticks(np.linspace(.5, levels - .5, levels))
ax.set_yticklabels(range(1, levels + 1))
ax.yaxis.set_tick_params(width=0)
ax.xaxis.set_tick_params(width=0)
ax.set_xticks(np.linspace(1, nodes, nodes))
ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10)
plt.ylabel('Link level')
plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total' + '_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight')
plt.close()
# plot all nodes normalised to usage of first level
usages = usageLevelsNorm.transpose()
plt.figure(figsize=(11, 3))
ax = plt.subplot()
plt.pcolormesh(usages[:, loadOrder], cmap=cmap)
plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11)
ax.set_yticks(np.linspace(.5, levels - .5, levels))
ax.set_yticklabels(range(1, levels + 1))
ax.yaxis.set_tick_params(width=0)
ax.xaxis.set_tick_params(width=0)
ax.set_xticks(np.linspace(1, nodes, nodes))
ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10)
plt.ylabel('Link level')
plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total_norm_cont_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight')
plt.close()
示例2: plot_response
def plot_response(data, plate_name, save_folder = 'Figures/'):
"""
"""
if not os.path.isdir(save_folder):
os.makedirs(save_folder)
for block in data:
#
group = group_similar(data[block].keys())
names = data[block].keys()
names.sort()
#
plt.figure(figsize=(16, 4 + len(names)/8), dpi=300)
#
for i, name in enumerate(names):
a, b, c = get_index(group, name)
color, pattern = color_shade_pattern(a, b, c, group)
mean = data[block][name]['mean'][0]
std = data[block][name]['std'][0]
plt.barh([i], [mean], height=1.0, color=color, hatch=pattern)
plt.errorbar([mean], [i+0.5], xerr=[std], ecolor = [0,0,0], linestyle = '')
plt.yticks([i+0.5 for i in xrange(len(names))], names, size = 8)
plt.title(plate_name)
plt.ylim(0, len(names))
plt.xlabel('change')
plt.tight_layout()
plt.savefig(save_folder + 'response_' + str(block + 1))
#
return None
示例3: plot_fit
def plot_fit(self, size=None, tol=0.1, axis_on=True):
n, d = self.D.shape
if size:
nrows, ncols = size
else:
sq = np.ceil(np.sqrt(n))
nrows = int(sq)
ncols = int(sq)
ymin = np.nanmin(self.D)
ymax = np.nanmax(self.D)
print 'ymin: {0}, ymax: {1}'.format(ymin, ymax)
numplots = np.min([n, nrows * ncols])
plt.figure()
for n in xrange(numplots):
plt.subplot(nrows, ncols, n + 1)
plt.ylim((ymin - tol, ymax + tol))
plt.plot(self.L[n, :] + self.S[n, :], 'r')
plt.plot(self.L[n, :], 'b')
if not axis_on:
plt.axis('off')
示例4: generate_start_time_figures
def generate_start_time_figures(self):
recording_time_grouped_by_patient = self.pain_data[["PatientID", "NRSTimeFromEndSurgery_mins"]].groupby("PatientID")
recording_start_minutes = recording_time_grouped_by_patient.min()
fig1 = "fig1.pdf"
fig2 = "fig2.pdf"
plt.figure(figsize=[8,4])
plt.title("Pain score recording start times", fontsize=14).set_y(1.05)
plt.ylabel("Occurrences", fontsize=14)
plt.xlabel("Recording Start Time (minutes)", fontsize=14)
plt.hist(recording_start_minutes.values, bins=20, color="0.5")
plt.savefig(os.path.join(self.tmp_directory, fig1), bbox_inches="tight")
plt.figure(figsize=[8,4])
plt.title("Pain score recording start times, log scale", fontsize=14).set_y(1.05)
plt.ylabel("Occurrences", fontsize=14)
plt.xlabel("Recording Start Time (minutes)", fontsize=14)
plt.hist(recording_start_minutes.values, bins=20, log=True, color="0.5")
plt.savefig(os.path.join(self.tmp_directory, fig2), bbox_inches="tight")
#save the figures in panel format
f = open(os.path.join(self.tmp_directory, "tmp.tex"), 'w')
f.write(r"""
\documentclass[%
,float=false % this is the new default and can be left away.
,preview=true
,class=scrartcl
,fontsize=20pt
]{standalone}
\usepackage[active,tightpage]{preview}
\usepackage{varwidth}
\usepackage{graphicx}
\usepackage[justification=centering]{caption}
\usepackage{subcaption}
\usepackage[caption=false,font=footnotesize]{subfig}
\renewcommand{\thesubfigure}{\Alph{subfigure}}
\begin{document}
\begin{preview}
\begin{figure}[h]
\begin{subfigure}{0.5\textwidth}
\includegraphics[width=\textwidth]{""" + fig1 + r"""}
\caption{Normal scale}
\end{subfigure}\begin{subfigure}{0.5\textwidth}
\includegraphics[width=\textwidth]{""" + fig2 + r"""}
\caption{Log scale}
\end{subfigure}
\end{figure}
\end{preview}
\end{document}
""")
f.close()
subprocess.call(["pdflatex",
"-halt-on-error",
"-output-directory",
self.tmp_directory,
os.path.join(self.tmp_directory, "tmp.tex")])
shutil.move(os.path.join(self.tmp_directory, "tmp.pdf"),
os.path.join(self.output_directory, "pain_score_start_times.pdf"))
示例5: plot
def plot(self, new_plot=False, xlim=None, ylim=None, title=None, figsize=None,
xlabel=None, ylabel=None, fontsize=None, show_legend=True, grid=True):
"""
Plot data using matplotlib library. Use show() method for matplotlib to see result or ::
%pylab inline
in IPython to see plot as cell output.
:param bool new_plot: create or not new figure
:param xlim: x-axis range
:param ylim: y-axis range
:type xlim: None or tuple(x_min, x_max)
:type ylim: None or tuple(y_min, y_max)
:param title: title
:type title: None or str
:param figsize: figure size
:type figsize: None or tuple(weight, height)
:param xlabel: x-axis name
:type xlabel: None or str
:param ylabel: y-axis name
:type ylabel: None or str
:param fontsize: font size
:type fontsize: None or int
:param bool show_legend: show or not labels for plots
:param bool grid: show grid or not
"""
xlabel = self.xlabel if xlabel is None else xlabel
ylabel = self.ylabel if ylabel is None else ylabel
figsize = self.figsize if figsize is None else figsize
fontsize = self.fontsize if fontsize is None else fontsize
self.fontsize_ = fontsize
self.show_legend_ = show_legend
title = self.title if title is None else title
xlim = self.xlim if xlim is None else xlim
ylim = self.ylim if ylim is None else ylim
new_plot = self.new_plot or new_plot
if new_plot:
plt.figure(figsize=figsize)
plt.xlabel(xlabel, fontsize=fontsize)
plt.ylabel(ylabel, fontsize=fontsize)
plt.title(title, fontsize=fontsize)
plt.tick_params(axis='both', labelsize=fontsize)
plt.grid(grid)
if xlim is not None:
plt.xlim(xlim)
if ylim is not None:
plt.ylim(ylim)
self._plot()
if show_legend:
plt.legend(loc='best', scatterpoints=1)
示例6: convert_all_to_png
def convert_all_to_png(vis_path, out_dir = "maps_png", size = None) :
units = { 'gas_density' : 'Gas Density [g/cm$^3$]',
'Tm' : 'Temperature [K]',
'Tew' : 'Temperature [K]',
'S' : 'Entropy []',
'dm' : 'DM Density [g/cm$^3$]',
'v' : 'Velocity [km/s]' }
log_list = ['gas_density']
for vis_file in os.listdir(vis_path) :
if ".dat" not in vis_file :
continue
print "converting %s" % vis_file
map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1)
(image, pixel_size, axis_values) = read_visualization_data(vis_path+"/"+vis_file, size)
print "image width in Mpc/h: ", axis_values[-1]*2.0
x, y = np.meshgrid( axis_values, axis_values )
cmap_max = image.max()
cmap_min = image.min()
''' plotting '''
plt.figure(figsize=(5,4))
if map_type in log_list:
plt.pcolor(x,y,image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min))
else :
plt.pcolor(x,y,image, vmax=cmap_max, vmin=cmap_min)
cbar = plt.colorbar()
if map_type in units.keys() :
cbar.ax.set_ylabel(units[map_type])
plt.axis([axis_values[0], axis_values[-1],axis_values[0], axis_values[-1]])
del image
plt.xlabel(r"$Mpc/h$", fontsize=18)
plt.ylabel(r"$Mpc/h$", fontsize=18)
out_file = vis_file.replace("dat", "png")
plt.savefig(out_dir+"/"+out_file, dpi=150 )
plt.close()
plt.clf()
示例7: drawAdoptionNetworkMPL
def drawAdoptionNetworkMPL(G, fnum=1, show=False, writeFile=None):
"""Draws the network to matplotlib, coloring the nodes based on adoption.
Looks for the node attribute 'adopted'. If the attribute is True, colors
the node a different color, showing adoption visually. This function assumes
that the node attributes have been pre-populated.
:param networkx.Graph G: Any NetworkX Graph object.
:param int fnum: The matplotlib figure number. Defaults to 1.
:param bool show:
:param str writeFile: A filename/path to save the figure image. If not
specified, no output file is written.
"""
Gclean = G.subgraph([n for n in G.nodes() if n not in nx.isolates(G)])
plt.figure(num=fnum, figsize=(6,6))
# clear figure
plt.clf()
# Blue ('b') node color for adopters, red ('r') for non-adopters.
nodecolors = ['b' if Gclean.node[n]['adopted'] else 'r' \
for n in Gclean.nodes()]
layout = nx.spring_layout(Gclean)
nx.draw_networkx_nodes(Gclean, layout, node_size=80,
nodelist=Gclean.nodes(),
node_color=nodecolors)
nx.draw_networkx_edges(Gclean, layout, alpha=0.5) # width=4
# TODO: Draw labels of Ii values. Maybe vary size of node.
# TODO: Color edges blue based on influences from neighbors
influenceEdges = []
for a in Gclean.nodes():
for n in Gclean.node[a]['influence']:
influenceEdges.append((a,n))
if len(influenceEdges)>0:
nx.draw_networkx_edges(Gclean, layout, alpha=0.5, width=5,
edgelist=influenceEdges,
edge_color=['b']*len(influenceEdges))
#some extra space around figure
plt.xlim(-0.05,1.05)
plt.ylim(-0.05,1.05)
plt.axis('off')
if writeFile != None:
plt.savefig(writeFile)
if show:
plt.show()
示例8: initWidgets
def initWidgets(self):
self.fig = plt.figure(1)
self.manager=get_current_fig_manager()
self.img = subplot(2,1,1)
self.TempGraph=subplot(2,1,2)
x1=sp.linspace(0.0,5.0)
y1=sp.cos(2*sp.pi*x1)*sp.exp(-x1)
plt.plot(x1,y1)
row=0
self.grid()
self.lblPower=tk.Label(self,text="Power")
self.lblPower.grid(row=row,column=0)
self.sclPower=tk.Scale(self,from_=0,to_=100000,orient=tk.HORIZONTAL)
self.sclPower.grid(row=row,column=1,columnspan=3)
#lastrow
row=row+1
self.btnOne=tk.Button(master=self,text="Run")
self.btnOne["command"]=self.Run
self.btnOne.grid(row=row,column=0)
self.btnTwo=tk.Button(master=self,text="Soak")
self.btnTwo["command"]=self.Soak
self.btnTwo.grid(row=row,column=2)
self.QUIT=tk.Button(master=self,text="QUIT")
self.QUIT["command"]=self.quit
self.QUIT.grid(row=row,column=3)
示例9: initWidgets
def initWidgets(self):
self.fig = plt.figure(1)
self.img = subplot(111)
self.manager=get_current_fig_manager()
self.img = subplot(2,1,2)
self.TempGraph=subplot(2,1,1)
row=0
self.grid()
self.lblPower=tk.Label(self,text="Power")
self.lblPower.grid(row=row,column=0)
self.sclPower=tk.Scale(self,from_=0,to_=100,orient=tk.HORIZONTAL)
self.sclPower.grid(row=row,column=1,columnspan=3)
row=row+1
self.lblTime=tk.Label(self,text="Time={0}".format(self.time))
self.lblTime.grid(row=row,column=0)
#lastrow
row=row+1
self.btnOne=tk.Button(master=self,text="Run")
self.btnOne["command"]=self.Run
self.btnOne.grid(row=row,column=0)
self.btnTwo=tk.Button(master=self,text="Soak")
self.btnTwo["command"]=self.Soak
self.btnTwo.grid(row=row,column=2)
self.QUIT=tk.Button(master=self,text="QUIT")
self.QUIT["command"]=self.quit
self.QUIT.grid(row=row,column=3)
示例10: createCoreDiffusionPlot
def createCoreDiffusionPlot(experimentCaseLog, outFilePath, plotTitle=None):
"""Function to generate the Core Diffusion vs Peripheral Density
plot. (Basically a clone of `createPeripheralDiffusionPlot`)
"""
# Generate plot of Core Diffusion vs. Nx density beyond the core
# x axis: pties/total possible ties
# y axis: # core adopters / # core nodes
mc = marker_cycle()
fig = plt.figure()
ax = fig.add_subplot(111)
for Ai in experimentCaseLog.keys():
# x axis is peripheral density, y axis is the core diffusion
x,y = experimentCaseLog[Ai][0], experimentCaseLog[Ai][2]
ax.plot(x,y, label="Ambiguity=%d"%Ai, marker=mc.next())
ax.set_xlabel("Network Density Beyond the Core")
ax.set_ylabel("Core Diffusion")
ax.legend(loc="best")
if plotTitle == None:
ax.set_title("Extent of Core Diffusion for Varying Ambiguity "
"and Network Density")
else:
ax.set_title(plotTitle)
outPlotFilename = "Plot-CoreDiffusionVsDensity.png"
fig.savefig(pathjoin(outFilePath, outPlotFilename))
示例11: render_confusion
def render_confusion(file_name, queue, vmin, vmax, divergent, array_shape):
from pylab import plt
import matplotlib.animation as animation
plt.close()
fig = plt.figure()
def update_img((expected, output)):
plt.cla()
plt.ylim((vmin, vmin+vmax))
plt.xlim((vmin, vmin+vmax))
ax = fig.add_subplot(111)
plt.plot([vmin, vmin+vmax], [vmin, vmin+vmax])
ax.grid(True)
plt.xlabel("expected output")
plt.ylabel("network output")
plt.legend()
expected = expected*vmax + vmin
output = output*vmax + vmin
#scat.set_offsets((expected, output))
scat = ax.scatter(expected, output)
return scat
ani = animation.FuncAnimation(fig, update_img, frames=IterableQueue(queue))
ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
示例12: main
def main():
s = 2.0
img = imread('cameraman.png')
# Create all the images with each a differen order of convolution
img1 = gD(img, s, 0, 0)
img2 = gD(img, s, 1, 0)
img3 = gD(img, s, 0, 1)
img4 = gD(img, s, 2, 0)
img5 = gD(img, s, 0, 2)
img6 = gD(img, s, 1, 1)
fig = plt.figure()
ax1 = fig.add_subplot(2, 3, 1)
ax1.set_title("Fzero")
ax1.imshow(img1, cmap=cm.gray)
ax2 = fig.add_subplot(2, 3, 2)
ax2.set_title("Fx")
ax2.imshow(img2, cmap=cm.gray)
ax3 = fig.add_subplot(2, 3, 3)
ax3.set_title("Fy")
ax3.imshow(img3, cmap=cm.gray)
ax4 = fig.add_subplot(2, 3, 4)
ax4.set_title("Fxx")
ax4.imshow(img4, cmap=cm.gray)
ax5 = fig.add_subplot(2, 3, 5)
ax5.set_title("Fyy")
ax5.imshow(img5, cmap=cm.gray)
ax6 = fig.add_subplot(2, 3, 6)
ax6.set_title("Fxy")
ax6.imshow(img6, cmap=cm.gray)
show()
示例13: plotter
def plotter(mode,Bc,Tc,Q):
col = ['#000080','#0000FF','#4169E1','#6495ED','#00BFFF','#B0E0E6']
plt.figure()
ax = plt.subplot(111)
for p in range(Bc.shape[1]):
plt.plot(Tc[:,p],Bc[:,p],'-',color=str(col[p]))
plt.xlabel('Tc [TW]')
plt.ylabel('Bc normalised to total EU load')
plt.title(str(mode)+' flow')
# Shrink current axis by 25% to make room for legend
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])
plt.legend(\
([str(Q[i]*100) for i in range(len(Q))]),\
loc='center left', bbox_to_anchor=(1, 0.5),title='Quantiles')
plt.savefig('figures/bctc_'+str(mode)+'.eps')
示例14: show_prediction_result
def show_prediction_result(image, label_image, clf):
size = (8, 8)
plt.figure(figsize=(15, 10))
plt.imshow(image, cmap='gray_r')
candidates = []
predictions = []
for region in regionprops(label_image):
# skip small images
# if region.area < 100:
# continue
# draw rectangle around segmented coins
minr, minc, maxr, maxc = region.bbox
# make regions square
maxwidth = np.max([maxr - minr, maxc - minc])
minr, maxr = int(0.5 * ((maxr + minr) - maxwidth)) - 3, int(0.5 * ((maxr + minr) + maxwidth)) + 3
minc, maxc = int(0.5 * ((maxc + minc) - maxwidth)) - 3, int(0.5 * ((maxc + minc) + maxwidth)) + 3
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2, alpha=0.2)
plt.gca().add_patch(rect)
# predict digit
candidate = image[minr:maxr, minc:maxc]
candidate = np.array(imresize(candidate, size), dtype=float)
# invert
# candidate = np.max(candidate) - candidate
# print im
# rescale to 16 in integer
candidate = (candidate - np.min(candidate))
if np.max(candidate) == 0:
continue
candidate /= np.max(candidate)
candidate[candidate < 0.2] = 0.0
candidate *= 16
candidate = np.array(candidate, dtype=int)
prediction = clf.predict(candidate.reshape(-1))
candidates.append(candidate)
predictions.append(prediction)
plt.text(minc - 10, minr - 10, "{}".format(prediction), fontsize=50)
plt.xticks([], [])
plt.yticks([], [])
plt.tight_layout()
plt.show()
return candidates, predictions
示例15: plotScale
def plotScale(imgFile, minVal, maxVal):
imgSize = (2, 4)
fig = plt.figure(figsize=imgSize, dpi=100, frameon=True, facecolor='w')
for i in xrange(10):
val = minVal + i * (maxVal - minVal) / 10
col = getColor(val, minVal, maxVal)
X = [float(i) / 10, float(i + 1) / 10, float(i + 1) / 10, float(i) / 10, float(i) / 10]
Y = [1, 1, 0, 0, 1]
fill(X, Y, col, lw=1, ec=col)
savefig(imgFile)
close()