本文整理汇总了Python中matplotlib.pyplot.gca函数的典型用法代码示例。如果您正苦于以下问题:Python gca函数的具体用法?Python gca怎么用?Python gca使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gca函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_scatter
def save_scatter(data, colours, title, ylabel, savePath, yLimTuple=None):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title(title)
plt.xlabel("Trials")
plt.ylabel(ylabel)
# Sort by value
data, colours = zip(*sorted(zip(data, colours)))
nov_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "r"]
inter_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "g"]
exp_data = [(i, d) for (i, d, c) in zip(range(len(data)), data, colours) if c == "b"]
nov = ax.scatter(zip(*nov_data)[0], zip(*nov_data)[1], color="r", marker="o", s=60)
inter = ax.scatter(zip(*inter_data)[0], zip(*inter_data)[1], color="g", marker="^", s=60)
exp = ax.scatter(zip(*exp_data)[0], zip(*exp_data)[1], color="b", marker="*", s=60)
plt.legend((nov, inter, exp), ["Novice", "Intermediate", "Expert"], loc=2)
plt.xticks([])
plt.gca().set_xlim(-1, len(data))
if yLimTuple:
plt.gca().set_xlim(yLimTuple)
plt.tight_layout()
with open(savePath, "w") as figOut:
plt.savefig(figOut)
示例2: vis_all_detection
def vis_all_detection(im_array, detections, imdb_classes=None, thresh=0.):
"""
visualize all detections in one image
:param im_array: [b=1 c h w] in rgb
:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
:param imdb_classes: list of names in imdb
:param thresh: threshold for valid detections
:return:
"""
import matplotlib.pyplot as plt
import random
im = image_processing.transform_inverse(im_array, config.PIXEL_MEANS)
plt.imshow(im)
for j in range(1, len(imdb_classes)):
color = (random.random(), random.random(), random.random()) # generate a random color
dets = detections[j]
for i in range(dets.shape[0]):
bbox = dets[i, :4]
score = dets[i, -1]
if score > thresh:
rect = plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor=color, linewidth=2)
plt.gca().add_patch(rect)
plt.gca().annotate('{} {:.3f}'.format(imdb_classes[j], score),
rect.get_xy(), color='w')
plt.show()
示例3: test_simple
def test_simple(self):
# First sub-plot
plt.subplot(221)
plt.title('Default')
iplt.contourf(self.cube)
plt.gca().coastlines()
# Second sub-plot
plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120))
plt.title('Molleweide')
iplt.contourf(self.cube)
plt.gca().coastlines()
# Third sub-plot (the projection part is redundant, but a useful
# test none-the-less)
ax = plt.subplot(223, projection=iplt.default_projection(self.cube))
plt.title('Native')
iplt.contour(self.cube)
ax.coastlines()
# Fourth sub-plot
ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree())
plt.title('PlateCarree')
iplt.contourf(self.cube)
ax.coastlines()
self.check_graphic()
示例4: plot
def plot(self):
if self.pos == None:
self.pos = nx.graphviz_layout(self)
NODE_SIZE = 500
plt.clf()
nx.draw_networkx_nodes(self, pos=self.pos,
nodelist=self.normal,
node_color=NORMAL_COLOR,
node_size=NODE_SIZE)
nx.draw_networkx_nodes(self, pos=self.pos,
nodelist=self.contam,
node_color=CONTAM_COLOR,
node_size=NODE_SIZE)
nx.draw_networkx_nodes(self, pos=self.pos,
nodelist=self.immune,
node_color=IMMUNE_COLOR,
node_size=NODE_SIZE)
nx.draw_networkx_nodes(self, pos=self.pos,
nodelist=self.dead,
node_color=DEAD_COLOR,
node_size=NODE_SIZE)
nx.draw_networkx_edges(self, pos=self.pos,
edgelist=self.nondead_edges(),
width=2,
edge_color='0.2')
nx.draw_networkx_labels(self, pos=self.pos,
font_color='0.95', font_size=11)
plt.gca().get_xaxis().set_visible(False)
plt.gca().get_yaxis().set_visible(False)
plt.draw()
示例5: _plot
def _plot(x, Y, file_name):
title = file_name.replace('_', ' ').upper()
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
plt.subplots_adjust(left=0.075, right=0.96, top=0.92, bottom=0.08)
#ax.set_autoscaley_on(False)
#ax.set_ylim([0,0.1])
ax.set_xlim(0, RANGE[1])
powerlaw = lambda x, amp, index: amp * (x**index)
for y in Y:
day, region = y
amp, index = DATA[day][region]
label = '{region} ({day})'.format(day=day, region=region).upper()
ax.plot(x, powerlaw(x, amp, index), label=label, linewidth=1, color=COLORS[region], alpha=0.95, linestyle=LINESTYLE[day])
formatter = FuncFormatter(lambda v, pos: str(round(v*100, 2))+'%')
plt.gca().yaxis.set_major_formatter(formatter)
formatter = FuncFormatter(lambda v, pos: '' if v/1000 == 0 else str(int(v/1000))+'km')
plt.gca().xaxis.set_major_formatter(formatter)
ax.set_title(title, fontsize=11)
ax.legend(fontsize=10)
if not os.path.exists('data/' + my.DATA_FOLDER + 'disp_stat/'):
os.makedirs('data/' + my.DATA_FOLDER + 'disp_stat/')
plt.savefig('data/' + my.DATA_FOLDER + 'disp_stat/' + file_name + '.png')
print 'Stored chart: %s' % file_name
示例6: main
def main():
fname = iris.sample_data_path('ostia_monthly.nc')
# load a single cube of surface temperature between +/- 5 latitude
cube = iris.load_cube(fname, iris.Constraint('surface_temperature', latitude=lambda v: -5 < v < 5))
# Take the mean over latitude
cube = cube.collapsed('latitude', iris.analysis.MEAN)
# Now that we have our data in a nice way, lets create the plot
# contour with 20 levels
qplt.contourf(cube, 20)
# Put a custom label on the y axis
plt.ylabel('Time / years')
# Stop matplotlib providing clever axes range padding
plt.axis('tight')
# As we are plotting annual variability, put years as the y ticks
plt.gca().yaxis.set_major_locator(mdates.YearLocator())
# And format the ticks to just show the year
plt.gca().yaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.show()
示例7: test_plot_tmerc
def test_plot_tmerc(self):
filename = tests.get_data_path(('NetCDF', 'transverse_mercator',
'tmean_1910_1910.nc'))
self.cube = iris.load_cube(filename)
iplt.pcolormesh(self.cube[0])
plt.gca().coastlines()
self.check_graphic()
示例8: main
def main():
fig,ax=plt.subplots()
ax.set_xlim([-0.5,2.5])
ax.set_ylim([-0.5,2.5])
deg=0
A=rot(-deg)@[email protected]([[np.sqrt(2),0],[0,1]])@rot(deg)
xy1=np.array([1,0])
transxy1=trans(A,xy1)
xy2=np.array([0,1])
transxy2=trans(A,xy2)
xy3=np.array([1,1])
transxy3=trans(A,xy3)
xy4=trans(rot(30),np.array([1,0]))
transxy4=trans(A,xy4)
plot_vector(ax,xy1,color=0.1)
plot_vector(ax,transxy1,color=0.1)
plot_vector(ax,xy2,color=0.2)
plot_vector(ax,transxy2,color=0.2)
plot_vector(ax,xy3,color=0.3)
plot_vector(ax,transxy3,color=0.3)
plot_vector(ax,xy4,color=0.4)
plot_vector(ax,transxy4,color=0.4)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
示例9: plot_bold_signal
def plot_bold_signal(timeseries, x, y):
# plots timeseries of two given nodes in a specific time interval
v1 = timeseries[:, x]
v2 = timeseries[:, y]
T = len(v1)
time = np.linspace(0, T-1, T) / float(60000)
[R_pearson , p_value] = sistat.pearsonr(v1 , v2)
## if the given signal downsampled :
#time_bds = np.arange(0, 530, float(530)/len(v1) )/float(60)
#pl.plot(time_bds, v1, 'r',label=('node '+str(x)))
#pl.plot(time_bds, v2, 'b',label=('node '+str(y)))
# if no downsampling :
fig , ax = pl.subplots(figsize=(25, 5.5))
pl.subplots_adjust(left=0.08, right=0.98, top=0.94, bottom=0.20)
pl.plot(time, v1, 'm', label=('$u_{' + str(x+1) + '}(t)$'))
pl.plot(time, v2, 'g', label=('$u_{' + str(y+1) + '}(t)$'))
pl.setp(pl.gca().get_xticklabels(), fontsize = 30)
pl.setp(pl.gca().get_yticklabels(), fontsize = 30)
#ax.set_ylim(-v2.max()-0.05, v2.max()+0.05)
ax.set_ylim(-0.6, 0.6)
pl.legend(prop={'size':35})
pl.xlabel('t [min]', fontsize=30)
pl.ylabel('BOLD % change' ,fontsize=40)
return
示例10: groupHourly
def groupHourly(dataGroup, names, title, timeShift, stacked=True,show=True):
plt.gca()
toPlot = []
namesShown = []
for pos in range(len(dataGroup)):
#for dataIn in dataGroup:
if len(dataGroup[pos]['data']) > 0:
data = truncData(dataGroup[pos]['data'],"hour")
dates = data['created_at']
dates = [parser.parse(date) for date in dates]
hour_list = [(t+timedelta(hours=timeShift)).hour for t in dates]
toPlot.append(hour_list)
namesShown.append(names[pos])
numbers=[x for x in xrange(0,25)]
labels=map(lambda x: str(x), numbers)
plt.xticks(numbers, labels)
plt.xlabel("Hour (GMT %s)" % timeShift)
plt.ylabel("Tweets")
if len(namesShown) != 0:
plt.title(title,size = 12)
plt.hist(toPlot,bins=numbers,stacked=stacked, alpha=0.5, label=names, align='mid')
plt.legend(namesShown,"best")
if show:
plt.show()
return plt
示例11: test_ts_plot_format_coord
def test_ts_plot_format_coord(self):
def check_format_of_first_point(ax, expected_string):
first_line = ax.get_lines()[0]
first_x = first_line.get_xdata()[0].ordinal
first_y = first_line.get_ydata()[0]
try:
self.assertEqual(expected_string,
ax.format_coord(first_x, first_y))
except (ValueError):
raise nose.SkipTest("skipping test because issue forming "
"test comparison GH7664")
annual = Series(1, index=date_range('2014-01-01', periods=3,
freq='A-DEC'))
check_format_of_first_point(annual.plot(), 't = 2014 y = 1.000000')
# note this is added to the annual plot already in existence, and
# changes its freq field
daily = Series(1, index=date_range('2014-01-01', periods=3, freq='D'))
check_format_of_first_point(daily.plot(),
't = 2014-01-01 y = 1.000000')
tm.close()
# tsplot
import matplotlib.pyplot as plt
from pandas.tseries.plotting import tsplot
tsplot(annual, plt.Axes.plot)
check_format_of_first_point(plt.gca(), 't = 2014 y = 1.000000')
tsplot(daily, plt.Axes.plot)
check_format_of_first_point(plt.gca(), 't = 2014-01-01 y = 1.000000')
示例12: plot_fgmax_grid
def plot_fgmax_grid():
fg = fgmax_tools.FGmaxGrid()
fg.read_input_data('fgmax_grid1.txt')
fg.read_output()
#clines_zeta = [0.01] + list(numpy.linspace(0.05,0.3,6)) + [0.5,1.0,10.0]
clines_zeta = [0.001] + list(numpy.linspace(0.05,0.25,10))
colors = geoplot.discrete_cmap_1(clines_zeta)
plt.figure(1)
plt.clf()
zeta = numpy.where(fg.B>0, fg.h, fg.h+fg.B) # surface elevation in ocean
plt.contourf(fg.X,fg.Y,zeta,clines_zeta,colors=colors)
plt.colorbar()
plt.contour(fg.X,fg.Y,fg.B,[0.],colors='k') # coastline
# plot arrival time contours and label:
arrival_t = fg.arrival_time/3600. # arrival time in hours
#clines_t = numpy.linspace(0,8,17) # hours
clines_t = numpy.linspace(0,2,5) # hours
#clines_t_label = clines_t[::2] # which ones to label
clines_t_label = clines_t[::1] # which ones to label
clines_t_colors = ([.5,.5,.5],)
con_t = plt.contour(fg.X,fg.Y,arrival_t, clines_t,colors=clines_t_colors)
plt.clabel(con_t, clines_t_label)
# fix axes:
plt.ticklabel_format(format='plain',useOffset=False)
plt.xticks(rotation=20)
plt.gca().set_aspect(1./numpy.cos(fg.Y.mean()*numpy.pi/180.))
plt.title("Maximum amplitude / arrival times (hrs)")
示例13: _plot_matplotlib
def _plot_matplotlib(obj, mesh, kwargs):
# Avoid importing until used
import matplotlib.pyplot as plt
gdim = mesh.geometry().dim()
if gdim == 3 or kwargs.get("mode") in ("warp",):
# Importing this toolkit has side effects enabling 3d support
from mpl_toolkits.mplot3d import axes3d
# Enabling the 3d toolbox requires some additional arguments
ax = plt.gca(projection='3d')
else:
ax = plt.gca()
ax.set_aspect('equal')
title = kwargs.pop("title", None)
if title is not None:
ax.set_title(title)
if isinstance(obj, cpp.Function):
return mplot_function(ax, obj, **kwargs)
elif isinstance(obj, cpp.Expression):
return mplot_expression(ax, obj, mesh, **kwargs)
elif isinstance(obj, cpp.Mesh):
return mplot_mesh(ax, obj, **kwargs)
elif isinstance(obj, cpp.DirichletBC):
return mplot_dirichletbc(ax, obj, **kwargs)
elif isinstance(obj, _meshfunction_types):
return mplot_meshfunction(ax, obj, **kwargs)
else:
raise AttributeError('Failed to plot %s' % type(obj))
示例14: update_figures
def update_figures(self):
plt.figure(self.figure.number)
x = np.arange(self.data.min(), self.data.max())#, (self.data.max() - self.data.min()) / 100) # artificial x-axis
# self.figure.gca().cla() # clearing the figure, just to be sure
# plt.subplot(411)
plt.plot(self.bins, self.hist, 'k')
plt.hold(True)
# if self.rv_heal is not None and self.rv_hypo is not None and self.rv_hyper is not None:
if self.models is not None:
healthy_y = self.rv_heal.pdf(x)
if self.unaries_as_cdf:
hypo_y = (1 - self.rv_hypo.cdf(x)) * self.rv_heal.pdf(self.rv_heal.mean())
hyper_y = self.rv_hyper.cdf(x) * self.rv_heal.pdf(self.rv_heal.mean())
else:
hypo_y = self.rv_hypo.pdf(x)
hyper_y = self.rv_hyper.pdf(x)
y_max = max(healthy_y.max(), hypo_y.max(), hyper_y.max())
fac = self.hist.max() / y_max
plt.plot(x, fac * healthy_y, 'g', linewidth=2)
plt.plot(x, fac * hypo_y, 'b', linewidth=2)
plt.plot(x, fac * hyper_y, 'r', linewidth=2)
if self.params and self.params.has_key('win_level') and self.params.has_key('win_width'):
ax = plt.axis()
border = 5
xmin = self.params['win_level'] - self.params['win_width'] / 2 - border
xmax = self.params['win_level'] + self.params['win_width'] / 2 + border
plt.axis([xmin, xmax, ax[2], ax[3]])
plt.gca().tick_params(direction='in', pad=1)
plt.hold(False)
# plt.grid(True)
self.canvas.draw()
示例15: el_plot
def el_plot(data, Map=False, show=True):
"""
Plot the elevation for the region from the last time series
:Parameters:
**data** -- the standard python data dictionary
**Map** -- {True, False} (optional): Optional argument. If True,
the elevation will be plotted on a map.
"""
trigrid = data['trigrid']
plt.gca().set_aspect('equal')
plt.tripcolor(trigrid, data['zeta'][-1,:])
plt.colorbar()
plt.title("Elevation")
if Map:
#we set the corners of where the map should show up
llcrnrlon, urcrnrlon = plt.xlim()
llcrnrlat, urcrnrlat = plt.ylim()
#we construct the map. Note that resolution serves to increase
#or decrease the detail in the coastline. Currently set to
#'i' for 'intermediate'
m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
resolution='i', suppress_ticks=False)
#set color for continents. Default is grey.
m.fillcontinents(color='ForestGreen')
m.drawmapboundary()
m.drawcoastlines()
if show:
plt.show()