def plot_kde(data, dir=None, filename="kde", color="Greens"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
bg_color = sns.color_palette(color, n_colors=256)[0]
ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
ax.set_axis_bgcolor(bg_color)
kde = ax.get_figure()
pylab.xlim(-4, 4)
pylab.ylim(-4, 4)
kde.savefig("{}/{}.png".format(dir, filename))
python类ylim()的实例源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
bg_color = sns.color_palette(color, n_colors=256)[0]
ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
ax.set_axis_bgcolor(bg_color)
kde = ax.get_figure()
pylab.xlim(-4, 4)
pylab.ylim(-4, 4)
kde.savefig("{}/{}".format(dir, filename))
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def plot_kde(data, dir=None, filename="kde", color="Greens"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
bg_color = sns.color_palette(color, n_colors=256)[0]
ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
ax.set_axis_bgcolor(bg_color)
kde = ax.get_figure()
pylab.xlim(-4, 4)
pylab.ylim(-4, 4)
kde.savefig("{}/{}.png".format(dir, filename))
def plot_kde(data, dir=None, filename="kde", color="Greens"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
bg_color = sns.color_palette(color, n_colors=256)[0]
ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
ax.set_axis_bgcolor(bg_color)
kde = ax.get_figure()
pylab.xlim(-4, 4)
pylab.ylim(-4, 4)
kde.savefig("{}/{}".format(dir, filename))
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
""" Plot multiples ROC curves as separate at the same painting area. """
pylab.clf()
pylab.title(title)
for ix, r in enumerate(rocList):
ax = pylab.subplot(4,4,ix+1)
pylab.ylim((0,1))
pylab.xlim((0,1))
ax.set_yticklabels([])
ax.set_xticklabels([])
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
if not labels:
labels = ['' for x in rocList]
pylab.text(0.2,0.1,labels[ix],fontsize=8)
pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)
pylab.show()
def plot(self,title='',include_baseline=False,equal_aspect=True):
""" Method that generates a plot of the ROC curve
Parameters:
title: Title of the chart
include_baseline: Add the baseline plot line if it's True
equal_aspect: Aspects to be equal for all plot
"""
pylab.clf()
pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
if include_baseline:
pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
pylab.ylim((0,1))
pylab.xlim((0,1))
pylab.xticks(pylab.arange(0,1.1,.1))
pylab.yticks(pylab.arange(0,1.1,.1))
pylab.grid(True)
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
pylab.xlabel('1 - Specificity')
pylab.ylabel('Sensitivity')
pylab.title(title)
pylab.show()
def data_loop(self):
import pylab
fig = pylab.figure()
pylab.ion()
while True:
fig.clear()
#pylab.plot(self.t[np.where(self.on==0)])
hz = 1000000 / self.delta
pylab.hist(hz, 50, range=(800, 1200))
pylab.xlim(500, 1500)
pylab.ylim(0, 100)
self.delta = self.delta[:0]
fig.canvas.draw()
fig.canvas.flush_events()
def plot_coverage(db,use_blacklist=True):
"""Plot the total covrage of the unbiased histogram.
>>> db = setup(pmfonly=True)
>>> db.add_metadata()
>>> plot_coverage(db)
Simple hard-coded plotting routine. Adds two dots for the end
points and focuses on the interesting region.
db pmfonly db
use_blacklist True: filter all files that appear in the blacklist [default]
"""
from pylab import clf,plot,xlim,ylim,title
if use_blacklist:
print "Excluding anything listed in the blacklist (i.e. restricting to __meta__)"
selection = db.selection("SELECT * FROM __data__")
else:
selection = db
selection.plot(mode="reldev")
#title(r'Umbrella sampling coverage: ${N}/{\langle{N}\rangle} - 1$')
make_canonical_plot()
def make_canonical_plot(NMP_lim=(39,76),LID_lim=(99,154),
c1AKE=config.angles['1AKE'],
c4AKE=config.angles['4AKE'],
xray=True):
"""Scale current figure to default limits and plot the positions of 1AKE and 4AKE.
The points for the end states are taken from txt/x-ray_angles.txt.
If xray=True then add locations of the X-ray structures; this is
the same as running plot_xary_structures().
"""
import pylab
if xray:
plot_xray_structures()
pylab.plot([c1AKE[0],c4AKE[0]], [c1AKE[1],c4AKE[1]], 'sw', ms=12, alpha=0.8)
pylab.xlim(NMP_lim)
pylab.ylim(LID_lim)
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):
nb_templates = templates.shape[1]
n_panels = numpy.ceil(numpy.sqrt(nb_templates))
mask = numpy.where(halo > -1)[0]
clust_idx = numpy.unique(halo[mask])
fig = pylab.figure()
square = True
center = len(data[0] - 1)//2
for count, i in enumerate(xrange(nb_templates)):
if square:
pylab.subplot(n_panels, n_panels, count + 1)
if (numpy.mod(count, n_panels) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_panels*(n_panels - 1)):
pylab.setp(pylab.gca(), xticks=[])
subcurves = numpy.where(halo == clust_idx[count])[0]
for k in numpy.random.permutation(subcurves)[:n_curves]:
pylab.plot(data[k], '0.5')
pylab.plot(templates[:, count], 'r')
pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)
xmin, xmax = pylab.xlim()
pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
#pylab.ylim(-1.5*threshold, 1.5*threshold)
ymin, ymax = pylab.ylim()
pylab.plot([center, center], [ymin, ymax], 'k--')
pylab.title('Cluster %d' %i)
if nb_templates > 0:
pylab.tight_layout()
if save:
pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def align_subplots(
N,
M,
xlim=None,
ylim=None,
):
"""make all of the subplots have the same limits, turn off unnecessary ticks"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
xlim[0] = min(xlim[0], pb.xlim()[0])
xlim[1] = max(xlim[1], pb.xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
ylim[0] = min(ylim[0], pb.ylim()[0])
ylim[1] = max(ylim[1], pb.ylim()[1])
for i in range(N * M):
pb.subplot(N, M, i + 1)
pb.xlim(xlim)
pb.ylim(ylim)
if i % M:
pb.yticks([])
else:
removeRightTicks()
if i < M * (N - 1):
pb.xticks([])
else:
removeUpperTicks()
def align_subplot_array(axes, xlim=None, ylim=None):
"""
Make all of the axes in the array hae the same limits, turn off unnecessary ticks
use pb.subplots() to get an array of axes
"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for ax in axes.flatten():
xlim[0] = min(xlim[0], ax.get_xlim()[0])
xlim[1] = max(xlim[1], ax.get_xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for ax in axes.flatten():
ylim[0] = min(ylim[0], ax.get_ylim()[0])
ylim[1] = max(ylim[1], ax.get_ylim()[1])
(N, M) = axes.shape
for (i, ax) in enumerate(axes.flatten()):
ax.set_xlim(xlim)
ax.set_ylim(ylim)
if i % M:
ax.set_yticks([])
else:
removeRightTicks(ax)
if i < M * (N - 1):
ax.set_xticks([])
else:
removeUpperTicks(ax)
def plot(self, bgimage=None):
import pylab as pl
self._plot_background(bgimage)
ax = pl.gca()
y0, y1 = pl.ylim()
# r is the width of the thick line we use to show the facade colors
r = 5
patch = pl.Rectangle((self.facade_left + r, self.sky_line + r),
self.width - 2 * r,
self.door_line - self.sky_line - 2 * r,
color=self.color, fill=False, lw=2 * r)
ax.add_patch(patch)
pl.text((self.facade_right + self.facade_left) / 2.,
(self.door_line + self.sky_line) / 2.,
'$\sigma^2={:0.2f}$'.format(self.uncertainty_for_windows()))
patch = pl.Rectangle((self.facade_left + r, self.door_line + r),
self.width - 2 * r,
y0 - self.door_line - 2 * r,
color=self.mezzanine_color, fill=False, lw=2 * r)
ax.add_patch(patch)
# Plot the left and right edges in yellow
pl.vlines([self.facade_left, self.facade_right], self.sky_line, y0, colors='yellow')
# Plot the door line and the roof line
pl.hlines([self.door_line, self.sky_line], self.facade_left, self.facade_right, linestyles='dashed',
colors='yellow')
self.window_grid.plot()
def plot_facade_cuts(self):
facade_sig = self.facade_edge_scores.sum(0)
facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount)
mu = np.mean(facade_sig)
sigma = np.std(facade_sig)
w = self.rectified.shape[1]
pad=10
gs1 = pl.GridSpec(5, 5)
gs1.update(wspace=0.5, hspace=0.0) # set the spacing between axes.
pl.subplot(gs1[:3, :])
pl.imshow(self.rectified)
pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
pl.axis('off')
pl.xlim(-pad, w+pad)
pl.subplot(gs1[3:, :], sharex=pl.gca())
pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue')
pl.plot(np.arange(w), facade_sig, color='blue')
pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black')
pl.scatter(facade_cuts, facade_sig[facade_cuts])
pl.axis('off')
pl.hlines(mu, 0, w, linestyle='dashed', color='black')
pl.text(0, mu, '$\mu$ ', ha='right')
pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',)
pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
pl.xlim(-pad, w+pad)
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):
logger = logging.getLogger("plotting")
logger.debug('MultipleSeriesPlot.generate_plot')
# a plot with one or more time series sharing a common x axis:
# e.g., the training error and the validation error plotted against epochs
# sort the data series and make sure they are consistent
self.sort_and_validate()
# if there is a plot already in existence, we will clear it and re-use it;
# this avoids creating extraneous figures which will stay in memory
# (even if we are no longer referencing them)
if self.plot:
self.plot.clf()
else:
# create a plot
self.plot = plt.figure()
splt = self.plot.add_subplot(1, 1, 1)
splt.set_title(title)
splt.set_xlabel(xlabel)
splt.set_ylabel(ylabel)
if xlim:
pylab.xlim(xlim)
if ylim:
pylab.ylim(ylim)
for series_name,data_points in self.data.items():
xpoints=numpy.asarray([seq[0] for seq in data_points])
ypoints=numpy.asarray([seq[1] for seq in data_points])
line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
logger.debug('set_label for %s' % series_name)
line.set_label(series_name)
splt.legend()
# TO DO - better filename configuration for plots
self.plot.savefig(filename)
def __init__(self):
pylab.ion()
self.com_real = []
self.com_ref = []
self.support_areas = []
self.xlabel = "$y$ (m)"
self.ylabel = "$x$ (m)"
self.xlim = (-0.6, 0.1)
self.ylim = (0. - 0.05, 1.4 + 0.05)
self.zmp_real = []
self.zmp_ref = []
def plot_com(self):
pylab.plot(
[-p[1] for p in self.com_real], [p[0] for p in self.com_real],
'g-', lw=2)
pylab.plot(
[-p[1] for p in self.com_ref], [p[0] for p in self.com_ref],
'k--', lw=1)
pylab.legend(('$p_G$', '$p_G^{ref}$'), loc='upper right')
pylab.grid(False)
pylab.xlim(self.xlim)
pylab.ylim(self.ylim)
pylab.xlabel(self.xlabel)
pylab.ylabel(self.ylabel)
pylab.title("COM trajectory")
def plot_zmp(self):
pylab.plot(
[-p[1] for p in self.zmp_real], [p[0] for p in self.zmp_real],
'r-', lw=2)
pylab.plot(
[-p[1] for p in self.zmp_ref], [p[0] for p in self.zmp_ref],
'k--', lw=1)
pylab.legend(('$p_Z$', '$p_Z^{ref}$'), loc='upper right')
pylab.grid(False)
pylab.xlim(self.xlim)
pylab.ylim(self.ylim)
pylab.xlabel(self.xlabel)
pylab.ylabel(self.ylabel)
pylab.title("ZMP trajectory")