本文整理汇总了Python中matplotlib.pyplot.sca函数的典型用法代码示例。如果您正苦于以下问题:Python sca函数的具体用法?Python sca怎么用?Python sca使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sca函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_some_shots
def plot_some_shots(run, ax=None):
file_name = h5_file_name_funk(run)
h5 = load_file(file_name)
spec_group = h5['spectral_properties']
#####
# Select region in the tree to get traces
# centers = (spec_group['center_eV'].value -
# h5['photoelectron_energy_prediction_eV'].value)
widths = spec_group['width_eV'].value
#I = np.abs(centers) < (center_max - center_min) / 10
# I = ((np.nanmax(widths) - (np.nanmax(widths) - np.nanmin(widths)) / 5) <
# widths)
I = np.isfinite(widths)
selected = np.random.choice(np.where(I)[0], 5)
selected.sort()
energy_scale_eV = h5['energy_scale_eV'].value
traces = h5['energy_signal'].value
if ax is None:
plt.figure('energy traces ' + str(run))
plt.clf()
else:
plt.sca(ax)
for shot in selected:
plt.plot(energy_scale_eV, traces[shot, :] * 1e3)
plt.xlim(70, 130)
示例2: demo_alternatinggraphcut
def demo_alternatinggraphcut():
t = 12
## Simulate small image
im, G = simulation.simulate_image(11,13,t,theta=0.4*np.pi )
# Show grid overlaid image
fig, ax = plt.subplots(1,2)
plt.sca(ax[0])
plt.imshow(im,cmap=plt.cm.gray)
plt.title('True grid')
plotgrid(G)
# Add random, disturbing, points
Nnew = 15
x_new = np.random.uniform(np.min(G.xy[:,0]),np.max(G.xy[:,0]), Nnew)
y_new = np.random.uniform(np.min(G.xy[:,1]),np.max(G.xy[:,1]), Nnew )
xy_new = np.vstack((x_new,y_new)).T
# Add to grid and make naive guess for edges
G.xy = np.vstack((G.xy,xy_new))
G.resolve_edges(remove_long=False)
# Show this modified grid
plt.sca(ax[1])
plotgrid(G)
plt.title('Modified/disturbed grid')
plt.show()
# Clean up using alternating graph cut
xy_hat, simplices_hat = alternating_graphcut.cleanup(G.xy,im,alpha=3,beta=2)
G_hat = grid.TriangularGrid.from_simplices(xy_hat,simplices_hat)
plt.figure()
plotgrid(G_hat)
plt.show(block=True)
示例3: plotBestFit
def plotBestFit(weights):
m = shape(dataMat)[0]
xcord1 = []
ycord1 = []
xcord2 = []
ycord2 = []
for i in range(m):
if labelMat[i] == 1:
xcord1.append(dataMat[i, 1])
ycord1.append(dataMat[i, 2])
else:
xcord2.append(dataMat[i, 1])
ycord2.append(dataMat[i, 2])
plt.figure(1)
ax = plt.subplot(111)
ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
ax.scatter(xcord2, ycord2, s=30, c='green')
x = arange(0.2, 0.8, 0.1)
y = array((-weights[0] - weights[1] * x) / weights[2])
print shape(x)
print shape(y)
plt.sca(ax)
plt.plot(x, y) # ramdomgradAscent
# plt.plot(x,y[0]) #gradAscent
plt.xlabel('density')
plt.ylabel('ratio_sugar')
# plt.title('gradAscent logistic regression')
plt.title('ramdom gradAscent logistic regression')
plt.show()
示例4: plot_marginals
def plot_marginals(self, func, **kwargs):
"""Draw univariate plots for `x` and `y` separately.
Parameters
----------
func : plotting callable
This must take a 1d array of data as the first positional
argument, it must plot on the "current" axes, and it must
accept a "vertical" keyword argument to orient the measure
dimension of the plot vertically.
kwargs : key, value mappings
Keyword argument are passed to the plotting function.
Returns
-------
self : JointGrid instance
Returns `self`.
"""
plt.sca(self.ax_marg_x)
func(self.x, **kwargs)
kwargs["vertical"] = True
plt.sca(self.ax_marg_y)
func(self.y, **kwargs)
return self
示例5: map_upper
def map_upper(self, func, **kwargs):
"""Plot with a bivariate function on the upper diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes.
"""
kw_color = kwargs.pop("color", None)
for i, j in zip(*np.triu_indices_from(self.axes, 1)):
hue_grouped = self.data.groupby(self.hue_vals)
for k, (label_k, data_k) in enumerate(hue_grouped):
ax = self.axes[i, j]
plt.sca(ax)
x_var = self.x_vars[j]
y_var = self.y_vars[i]
color = self.palette[k] if kw_color is None else kw_color
func(data_k[x_var], data_k[y_var], label=label_k,
color=color, **kwargs)
self._clean_axis(ax)
self._update_legend_data(ax)
if kw_color is not None:
kwargs["color"] = kw_color
示例6: niceplot
def niceplot(ax=None, axfs='12', lfs='14', tightlayout=True,
mew=1.25, lw=2.0, ms=7.0, **kwargs):
"""Pretty up a plot for publication.
Parameters
----------
ax : matplotlib.axes.AxesSubplot, optional
An axis to niceify. Default is all axes in the current figure.
axfs : string, float, or int, optional
Axis tick label font size.
lfs : string, float, or int, optional
Axis label font size.
tightlayout : bool, optional
Run `plt.tight_layout`.
**kwargs
Any line or marker property keyword.
"""
import matplotlib.pyplot as plt
if ax is None:
for ax in plt.gcf().get_axes():
niceplot(ax, tightlayout=tightlayout, axfs=axfs, lfs=lfs, **kwargs)
# for the axes
plt.setp(ax.get_ymajorticklabels(), fontsize=axfs)
plt.setp(ax.get_xmajorticklabels(), fontsize=axfs)
# axis labes
labels = (ax.xaxis.get_label(), ax.yaxis.get_label())
plt.setp(labels, fontsize=lfs)
# for plot markers, ticks
lines = ax.get_lines()
mew = kwargs.pop('markeredgewidth', kwargs.pop('mew', None))
if mew is not None:
plt.setp(lines, mew=mew)
ms = kwargs.pop('markersize', kwargs.pop('ms', None))
if ms is not None:
plt.setp(lines, ms=ms)
lw = kwargs.pop('linewidth', kwargs.pop('lw', None))
if lw is not None:
plt.setp(lines, lw=lw)
if len(kwargs) > 0:
plt.setp(lines, **kwargs)
lines = ax.xaxis.get_minorticklines() + ax.xaxis.get_majorticklines() + \
ax.yaxis.get_minorticklines() + ax.yaxis.get_majorticklines()
plt.setp(lines, mew=1.25)
# the frame
plt.setp(ax.patch, lw=2.0)
if hasattr(plt, "tight_layout") and tightlayout:
plt.sca(ax)
plt.tight_layout()
示例7: plot_locations
def plot_locations(self, ax=None, lu=None):
if self.annotations_loaded == False:
return
if ax is None:
fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5))
else:
pl.sca(ax)
if lu is None:
lu = (self.meta['start'], self.meta['end'])
palette = it.cycle(sns.husl_palette())
offsets = self.get_offsets()
for ai in xrange(self.num_annotators):
col = next(palette)
offset = offsets[ai]
for index, rr in slice_df_start_stop(self.locations[ai], lu).iterrows():
pl.plot([rr['start'], rr['end']], [self.location_targets.index(rr['name']) + offset * 2] * 2, color=col,
linewidth=5, alpha=0.5)
pl.yticks(np.arange(len(self.location_targets)), self.location_targets)
pl.ylim((-1, len(self.location_targets)))
pl.xlim(lu)
示例8: update
def update(self, t, alpha, beta, x_basis=False):
from matplotlib import pyplot as pl
ax = self.ax
pl.sca(ax)
pl.cla()
x_basis = self.x_basis
if x_basis:
from sglib import ip, col
from numpy import sqrt
alpha_x = ip(col(1,1)/sqrt(2), col(alpha,beta))
beta_x = ip(col(1,-1)/sqrt(2), col(alpha,beta))
alpha = alpha_x; beta = beta_x
prob_plus = alpha*alpha.conjugate()
prob_minus = beta*beta.conjugate()
pos_plus = self.pos_plus
pos_minus = self.pos_minus
width = self.width
p1 = pl.bar([pos_plus], prob_plus, width, color='blue')
p2 = pl.bar([pos_minus], prob_minus, width, color='red')
pl.xticks(self.xticks, self.xlabels)
pl.ylabel('Probability')
pl.yticks(self.yticks)
pl.xlim(0, 1.1)
pl.ylim(0, 1.1)
pl.draw()
pl.show()
示例9: visualize_predictions
def visualize_predictions(prediction_seqs, label_seqs, num_classes,
fig_width=6.5, fig_height_per_seq=0.5):
""" Visualize predictions vs. ground truth.
Args:
prediction_seqs: A list of int NumPy arrays, each with shape
`[duration, 1]`.
label_seqs: A list of int NumPy arrays, each with shape `[duration, 1]`.
num_classes: An integer.
fig_width: A float. Figure width (inches).
fig_height_per_seq: A float. Figure height per sequence (inches).
Returns:
A tuple of the created figure, axes.
"""
num_seqs = len(label_seqs)
max_seq_length = max([seq.shape[0] for seq in label_seqs])
figsize = (fig_width, num_seqs*fig_height_per_seq)
fig, axes = plt.subplots(nrows=num_seqs, ncols=1,
sharex=True, figsize=figsize)
for pred_seq, label_seq, ax in zip(prediction_seqs, label_seqs, axes):
plt.sca(ax)
plot_label_seq(label_seq, num_classes, 1)
plot_label_seq(pred_seq, num_classes, -1)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.xlim(0, max_seq_length)
plt.ylim(-2.75, 2.75)
plt.tight_layout()
return fig, axes
示例10: draw_all
def draw_all(self):
for i in range(0, len(self.cpustats)):
ax = plt.subplot(2, len(self.cpustats)/2, i)
plt.sca(ax)
self.draw(self.cpustats[i], plt)
plt.show()
示例11: updateImage
def updateImage(self):
# clear plot
plt.sca(self.ax)
plt.cla()
self.initImage()
# Fetch data from SQL database
# try:
if self.current_plot == 'time_stack':
x,y = self.main_widget.imageAquisitionTab.stack.fetch_mologram_data()
elif self.current_plot == 'post_processing':
x,y = self.main_widget.postProcessingTab.get_time_and_molo_intensity()
else:
print('Current plot is empty')
return
# except Exception:
# print('Couldn\'t get data to plot')
# return
# plot appearance
plt.xlim([0, np.amax(x)])
plt.ylim([np.amin(y),np.amax(y)])
self.figure.tight_layout()
# add titles
self.ax.set_xlabel('Time (s)')
self.ax.set_ylabel('Mologram Intensity (arbitrary units)')
self.ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
# plot data and show canvas
self.points = plt.plot(x,y)
self.canvas.draw()
示例12: map
def map(self, func, *args, **kwargs):
"""
Apply a plotting function to each facet's subset of the data.
Parameters
----------
func : callable
A plotting function that takes data and keyword arguments. It
must plot to the currently active matplotlib Axes and take a
`color` keyword argument. If faceting on the `hue` dimension,
it must also take a `label` keyword argument.
args : strings
Column names in self.data that identify variables with data to
plot. The data for each variable is passed to `func` in the
order the variables are specified in the call.
kwargs : keyword arguments
All keyword arguments are passed to the plotting function.
Returns
-------
self : FacetGrid object
"""
import matplotlib.pyplot as plt
for ax, namedict in zip(self.axes.flat, self.name_dicts.flat):
if namedict is not None:
data = self.data[namedict]
plt.sca(ax)
innerargs = [data[a].values for a in args]
func(*innerargs, **kwargs)
return self
示例13: plot_confusion_matrix
def plot_confusion_matrix(cm, classes, ax,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
print(cm)
print('')
ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.set_title(title)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.sca(ax)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
ax.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
示例14: visualize
def visualize(model, filename):
values = model.all_params()
cols = OrderedDict()
for key, value in values.items():
if isinstance(value, np.ndarray): # TODO group by prefix, showing W and b side by side
cols.setdefault(key[:-2] + key[-1] if len(key) > 1 and key[-2] in "bW" else key, []).append((key, value))
_, axes = plt.subplots(2, len(cols), figsize=(5*len(cols), 10)) # TODO https://stackoverflow.com/a/13784887/223267
plt.tight_layout()
for j, col in enumerate(tqdm(cols.values(), unit="param", desc=filename)):
for i in range(2):
axis = axes[i, j] if len(values) > 1 else axes
if len(col) <= i:
plt.delaxes(axis)
else:
plt.sca(axis)
key, value = col[i]
plt.colorbar(plt.pcolormesh(smooth(value)))
for pattern, repl in REPLACEMENTS: # TODO map 0123->ifoc
key = re.sub(pattern, repl, key)
plt.title(key)
for axis in (plt.gca().xaxis, plt.gca().yaxis):
axis.set_major_locator(MaxNLocator(integer=True))
output_file = filename + ".png"
plt.savefig(output_file)
plt.clf()
print("Saved '%s'." % output_file)
示例15: plot
def plot(w):
dataMat=np.array(df[['density','ratio_sugar']].values[:,:])
labelMat=np.mat(df['good'].values[:]).transpose()
m=np.shape(dataMat)[0]
xcord1=[]
ycord1=[]
xcord2=[]
ycord2=[]
for i in range(m):
if labelMat[i]==1:
xcord1.append(dataMat[i,0])
ycord1.append(dataMat[i,1])
else:
xcord2.append(dataMat[i,0])
ycord2.append(dataMat[i,1])
plt.figure(1)
ax=plt.subplot(111)
ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
ax.scatter(xcord2,ycord2,s=30,c='green')
x=np.arange(-0.2,0.8,0.1)
y=np.array((-w[0,0]*x)/w[0,1])
plt.sca(ax)
plt.plot(x,y) #gradAscent
plt.xlabel('density')
plt.ylabel('ratio_sugar')
plt.title('LDA')
plt.show()