def __axes_spmap(self): for x in xrange(self.nh): for y in xrange(self.nv): w = self.horizontal_subplot_size h = self.vertical_subplot_size l = 1.0 - self.right_margin - w * ( x + 1) + 0.5 * self.horizontal_space b = self.bottom_margin + self.ylabel_area + h * y + 0.5 * self.vertical_space axes = pl.axes( [l, b, w - self.horizontal_space, h - self.vertical_space]) axes.cla() if self.showaxislabel and y == 0 and x == self.nh - 1: casalog.post('label "{label}" unit "{unit}"'.format( label=self.spectral_label, unit=self.spectral_unit), priority='DEBUG') if self.spectral_unit is not None and len( self.spectral_unit) > 0: spectral_label = '%s [%s]' % (self.spectral_label, self.spectral_unit) else: spectral_label = self.spectral_label axes.xaxis.set_label_text(spectral_label, size=self.ticksize) if self.normalization_factor < 100 and self.normalization_factor > 0.01: label_text = 'Intensity [%s]' % self.brightnessunit else: label_text = 'Intensity [1e%d x %s]' % ( int(numpy.log10(self.normalization_factor)), self.brightnessunit) axes.yaxis.set_label_text(label_text, size=self.ticksize, rotation='vertical') if self.showtick: axes.xaxis.tick_bottom() axes.yaxis.tick_left() if self.showticklabel: xlocator = pl.AutoLocator() xlocator.set_params(nbins=6, prune='upper') axes.xaxis.set_major_locator(xlocator) ylocator = pl.AutoLocator() ylocator.set_params(nbins=4) axes.yaxis.set_major_locator(ylocator) xformatter = pl.ScalarFormatter(useOffset=False) axes.xaxis.set_major_formatter(xformatter) axes.xaxis.set_tick_params( labelsize=max(self.ticksize - 1, 1)) axes.yaxis.set_tick_params( labelsize=max(self.ticksize - 1, 1)) if y != 0 or x != self.nh - 1: axes.xaxis.set_major_formatter(pl.NullFormatter()) axes.yaxis.set_major_formatter(pl.NullFormatter()) else: axes.xaxis.set_major_formatter(pl.NullFormatter()) axes.yaxis.set_major_formatter(pl.NullFormatter()) else: axes.yaxis.set_major_locator(pl.NullLocator()) axes.xaxis.set_major_locator(pl.NullLocator()) yield axes
def plot(ifiles, args): from PseudoNetCDF.coordutil import getsigmamid, getpresmid, gettimes import pylab as pl from pylab import figure, NullFormatter, close, rcParams rcParams['text.usetex'] = False from matplotlib.colors import LinearSegmentedColormap, BoundaryNorm, LogNorm scale = args.scale; minmax = eval(args.minmax) minmaxq = eval(args.minmaxq) sigma = args.sigma maskzeros = args.maskzeros outunit = args.outunit tespaths = args.tespaths omipaths = args.omipaths edges = args.edges try: f, = ifiles except: raise ValueError('curtain plot expects one file when done. Try stack time --stack=time to concatenate') # Add CF conventions if necessary if 'latitude_bounds' not in f.variables.keys(): try: from PseudoNetCDF import getvarpnc from PseudoNetCDF.conventions.ioapi import add_cf_from_ioapi f = getvarpnc(f, None) add_cf_from_ioapi(f) except: pass if sigma: vertcrd = getsigmamid(f) else: vertcrd = getpresmid(f, pref = 101325., ptop = getattr(f, 'VGTOP', 10000)) if vertcrd.max() > 2000: vertcrd /= 100. try: lonb = f.variables['geos_longitude_bounds'] latb = f.variables['geos_latitude_bounds'] except: lonb = f.variables['longitude_bounds'] latb = f.variables['latitude_bounds'] for var_name in args.variables: temp = defaultdict(lambda: 1) try: eval(var_name, None, temp) var = eval(var_name, None, f.variables)[:] except: temp[var_name] var = f.variables[var_name][:] if maskzeros: var = np.ma.masked_values(var, 0) unit = f.variables[temp.keys()[0]].units.strip() if unit in unitconvert: var = unitconvert.get((unit, outunit), lambda x: x)(var) else: outunit = unit bmap = None vmin, vmax = np.percentile(np.ma.compressed(var).ravel(), list(minmaxq)) if minmax[0] is not None: vmin = minmax[0] if minmax[1] is not None: vmax = minmax[1] if edges: fig = pl.figure(figsize = (16, 4)) offset = 0.05 ax = fig.add_axes([.1 - offset, .15, .22, .725]) ax = fig.add_axes([.325 - offset, .15, .22, .725]) ax = fig.add_axes([.55 - offset, .15, .22, .725]) ax = fig.add_axes([.775 - offset, .15, .22, .725]) ss = 0 se = ss + f.NCOLS + 1 es = se ee = se + f.NROWS + 1 ns = ee ne = ee + f.NCOLS + 1 ws = ne we = ws + f.NROWS + 1 axs = fig.axes for ax in fig.axes[1:]: ax.yaxis.set_major_formatter(pl.NullFormatter()) vars = [var[:, :, ss:se], var[:, :, es:ee], var[:, :, ns:ne][:, :, ::-1], var[:, :, ws:we][:, :, ::-1]] lonbss = [lonb[ss:se], lonb[es:ee], lonb[ns:ne][::-1], lonb[ws:we][::-1]] latbss = [latb[ss:se], latb[es:ee], latb[ns:ne][::-1], latb[ws:we][::-1]] else: fig = pl.figure(figsize = (8, 4)) ax = fig.add_axes([.1, .15, .8, .725]) axs = fig.axes vars = [var] lonbss = [lonb[:]] latbss = [latb[:]] for ax, var, lonbs, latbs in zip(axs, vars, lonbss, latbss): vals = var.swapaxes(0, 1).reshape(var.shape[1], -1) ax.text(.05, .9, 'n = %d' % vals.shape[1], transform = ax.transAxes) modl, modr = minmaxmean(ax, vals, vertcrd, facecolor = 'k', edgecolor = 'k', alpha = .2, zorder = 4, label = 'GC', ls = '-', lw = 2, color = 'k') llines = [(modl, modr)] ymin, ymax = vertcrd.min(), vertcrd.max() ax.set_ylim(ymax, ymin) ax.set_xscale(scale) ax.set_xlim(vmin, vmax) #if scale == 'log': # ax.set_xticklabels(['%.1f' % (10**x) for x in ax.get_xticks()]) if 'TFLAG' in f.variables.keys(): SDATE = f.variables['TFLAG'][:][0, 0, 0] EDATE = f.variables['TFLAG'][:][-1, 0, 0] STIME = f.variables['TFLAG'][:][0, 0, 1] ETIME = f.variables['TFLAG'][:][-1, 0, 1] if SDATE == 0: SDATE = 1900001 EDATE = 1900001 sdate = datetime.strptime('%07d %06d' % (SDATE, STIME), '%Y%j %H%M%S') edate = datetime.strptime('%07d %06d' % (EDATE, ETIME), '%Y%j %H%M%S') elif 'tau0' in f.variables.keys(): sdate = datetime(1985, 1, 1, 0) + timedelta(hours = f.variables['tau0'][0]) edate = datetime(1985, 1, 1, 0) + timedelta(hours = f.variables['tau1'][-1]) else: times = gettimes(f) sdate = times[0] edate = times[-1] if len(tespaths) > 0: tesl, tesr = plot_tes(ax, lonbs, latbs, tespaths) if not tesl is None: llines.append((tesl, tesr)) if len(omipaths) > 0: omil, omir = plot_omi(ax, lonbs, latbs, omipaths, airden = f.variables['AIRDEN'][:].mean(0).mean(1), airdenvert = vertcrd) if not omil is None: llines.append((omil, omir)) try: title = '%s to %s' % (sdate.strftime('%Y-%m-%d'), edate.strftime('%Y-%m-%d')) except: title = var_name if sigma: axs[0].set_ylabel('sigma') else: axs[0].set_ylabel('pressure') xmax = -np.inf xmin = np.inf for ax in fig.axes: tmp_xmin, tmp_xmax = ax.get_xlim() xmax = max(tmp_xmax, xmax) xmin = min(tmp_xmin, xmin) for ax in fig.axes: ax.set_xlim(xmin, xmax) if len(axs) == 1: axs[0].set_xlabel('%s %s' % (var_name, outunit)) else: axs[0].set_xlabel('South') axs[1].set_xlabel('East') axs[2].set_xlabel('North') axs[3].set_xlabel('West') fig.text(.5, .90, '%s %s' % (var_name, outunit), horizontalalignment = 'center', fontsize = 16) nl = 0 for ax in axs: if len(ax.get_lines()) > nl: nl = len(ax.get_lines()) pl.sca(ax) llabels = [l[0].get_label() for l in llines] pl.legend(llines, llabels, bbox_to_anchor = (.1, 1), loc = 'upper left', bbox_transform = fig.transFigure, ncol = 6) if edges: fig.text(0.95, 0.975, title, horizontalalignment = 'right', verticalalignment = "top", fontsize = 16) else: fig.text(0.95, 0.025, title, horizontalalignment = 'right', verticalalignment = "bottom", fontsize = 16) fig.savefig('%s_%s.%s' % (args.outpath, var_name, args.figformat)) pl.close(fig) return fig
# Plot 1D PDF, defined in subroutine below dummy,estimate = pappy.pdf1d(d1,wht,bins[i],smooth[i],color) print " Par no.",col+1,",",labels[col],"=",estimate if k == 0: hmax[i] = dummy # Write the estimate on the plot? # Force axes to obey limits: pylab.axis([limits[i,0],limits[i,1],0.0,1.2*hmax[i]]) # Adjust axes of 1D plots: ax = pylab.gca() # Turn off the y axis tick labels for all 1D panels: ax.yaxis.set_major_formatter(pylab.NullFormatter()) # Turn off the x axis tick labels for all but the last 1D panel: if j<(npars-1): ax.xaxis.set_major_formatter(pylab.NullFormatter()) pylab.xticks(rotation=45) # Label x axis, only on the bottom panels: if j==npars-1: pylab.xlabel(labels[col]) plottedsomething = True elif plot2D and j!=i: # Move to next subplot: if plot1D: panel = j*ngrid+i+1 else:
def jeans_maps(regions, size=u.Quantity([2.25, 2.25], u.arcsec), smooth=0): names = [r.attr[1]['text'] for r in regions] center_positions = coordinates.SkyCoord([r.coord_list for r in regions], unit=(u.deg, u.deg), frame='fk5') fn = "W51_te_continuum_best.fits" fh = fits.open(paths.dpath(fn)) mywcs = wcs.WCS(fh[0].header) bm = radio_beam.Beam.from_fits_header(fh[0].header) pixscale = (mywcs.pixel_scale_matrix.diagonal()**2).sum()**0.5 * u.deg pixscale_cm = (pixscale * masscalc.distance).to(u.cm, u.dimensionless_angles()) ppbeam = (bm.sr / (pixscale**2)).decompose().value / u.beam mass_maps = {} for ii, (name, position) in enumerate(zip(names, center_positions)): cutout = Cutout2D(fh[0].data, position, size, wcs=mywcs) source = 'e2' if name == 'e2e' else name temperature_map_fn = paths.dpath( '12m/moments/CH3OH_{0}_cutout_temperaturemap.fits'.format(source)) temperature_map_fh = fits.open(temperature_map_fn) # this whole section is copied from overlay_contours_on_ch3oh #ch3ohN_hdul = fits.open(paths.dpath('12m/moments/CH3OH_{0}_cutout_columnmap.fits'.format(source))) #ch3ohT_hdul = fits.open(paths.dpath('12m/moments/CH3OH_{0}_cutout_temperaturemap.fits'.format(source))) #bigwcs = wcs.WCS(ch3ohT_hdul[0].header) #bigpixscale = (bigwcs.pixel_scale_matrix.diagonal()**2).sum()**0.5 * u.deg #ch3ohN = ch3ohN_hdul[0].data #ch3ohT = ch3ohT_hdul[0].data #dust_brightness,wts = reproject.reproject_interp(fits.open(paths.dpath('W51_te_continuum_best.fits')), # ch3ohN_hdul[0].header) temwcs = wcs.WCS(temperature_map_fh[0].header) temcutout = Cutout2D(temperature_map_fh[0].data, position, size, wcs=temwcs) #maskcutout = Cutout2D(mask.astype('float'), position, size, wcs=bigwcs) tem_pixscale = (temwcs.pixel_scale_matrix.diagonal()** 2).sum()**0.5 * u.deg ppbeam_tem = ppbeam * (pixscale / tem_pixscale)**2 print("ppbeam, ppbeam_tem: ", ppbeam, ppbeam_tem) # geometric average FWHM bm_cm_fwhm = ((bm.major * bm.minor)**0.5 * masscalc.distance).to( u.cm, u.dimensionless_angles()) bm_cm = bm_cm_fwhm / (8 * np.log(2))**0.5 if smooth != 0: stddev_pix = ((smooth**2 / (8 * np.log(2)) - bm_cm**2)**0.5 / pixscale_cm).decompose() print('stddev_pix: {0}'.format(stddev_pix.decompose())) kernel = Gaussian2DKernel(stddev_pix) kernel.normalize('peak') #smdata = convolve(cutout.data / ppbeam, kernel) mass_map = (cutout.data * masscalc.mass_conversion_factor(TK=temcutout.data)).to( u.M_sun) # mass_map is the sum over a gaussian 'aperture', but it has to account for the # beam to avoid double-counting # (this is better than using smooth temperature, since that leads to a huge overestimate) new_ppbeam = (2 * np.pi * smooth**2 / (8 * np.log(2)) / pixscale_cm**2).decompose() / u.beam print('new_ppbeam: {0}, ppbeam: {1}, old_ppbeam: {2}'.format( new_ppbeam, ppbeam_tem, 2 * np.pi * (bm_cm / pixscale_cm).decompose()**2)) mass_map = convolve(mass_map, kernel) * u.M_sun * ( ppbeam / new_ppbeam).decompose() # temperature should be the average temperature kernel.normalize('integral') temmap = convolve(temcutout.data, kernel) #mass_map = (smdata * masscalc.mass_conversion_factor(TK=temcutout.data)).to(u.M_sun) bm_cm = smooth / (8 * np.log(2))**0.5 else: mass_map = (cutout.data * masscalc.mass_conversion_factor(TK=temcutout.data)).to( u.M_sun) temmap = temcutout.data # volume of a gaussian: sqrt(2 pi)^N r^N volume = (2 * np.pi)**(1.5) * bm_cm**3 density_map = (mass_map / volume / (2.8 * u.Da)).to(u.cm**-3) print("Scale: {0}".format(bm_cm.to(u.au))) c_s_map = ((constants.k_B * temmap * u.K / (2.4 * u.Da))**0.5).to( u.km / u.s) MJ_map_ = (np.pi / 6. * c_s_map**3 / (constants.G**1.5 * (2.8 * u.Da * density_map)**0.5)).to( u.M_sun) LJ_map = (c_s_map / (constants.G**0.5 * (2.8 * u.Da * density_map)**0.5)).to(u.au) MJ_map = (4 / 3. * np.pi * (LJ_map / 2.)**3 * (2.8 * u.Da * density_map)).to(u.M_sun) np.testing.assert_almost_equal(MJ_map.value, MJ_map_.value) fig = pl.figure(ii) fig.clf() ax1 = pl.subplot(2, 3, 1) im1 = ax1.imshow(mass_map.value, cmap='gray', vmin=0, vmax=10) ax1.set_title("Measured mass") fig.colorbar(im1) ax2 = pl.subplot(2, 3, 2) im2 = ax2.imshow(MJ_map.value, cmap='gray', vmin=0, vmax=10) ax2.set_title("Jeans mass") fig.colorbar(im2) ax3 = pl.subplot(2, 3, 3) ax3.set_title("Black: unstable") # 1 -> white # 0 -> black # mass > M_J = unstable # M_J > mass = stable = 1 = white ax3.imshow(MJ_map > mass_map, cmap='gray', vmin=0, vmax=1) ax4 = pl.subplot(2, 3, 4) ax4.set_title("log Density") im4 = ax4.imshow(np.log10(density_map.value), cmap='gray', vmin=7, vmax=9.5) fig.colorbar(im4) ax5 = pl.subplot(2, 3, 5) ax5.set_title("Temperature") im5 = ax5.imshow(temmap, cmap='gray', vmin=0, vmax=700) fig.colorbar(im5) ax6 = pl.subplot(2, 3, 6) im6 = ax6.imshow(LJ_map.value, cmap='gray', vmin=0, vmax=1e4) ax6.contourf(LJ_map.value, levels=[ 0, 2 * (bm_cm_fwhm.to(u.au)).value * gaussian_fwhm_to_sphere_r ], colors=['r', 'r']) ax6.set_title("Jeans Length (AU)") fig.colorbar(im6) for jj in range(1, 7): pl.subplot(2, 3, jj).xaxis.set_major_formatter(pl.NullFormatter()) pl.subplot(2, 3, jj).yaxis.set_major_formatter(pl.NullFormatter()) if smooth == 0: fig.savefig(paths.fpath("jeans_maps_{0}.png".format(name))) else: fig.savefig( paths.fpath("jeans_maps_{0}_smooth{1}.png".format( name, smooth))) mass_maps[name] = (mass_map, MJ_map) return mass_maps
def plot_data(self, sn=None, i_minq=0.02, i_maxq=0.05, flowrate=0, plot_merged=False, ymin=-1, ymax=-1, offset=0, uv_scale=1, showFWHM=False, calc_Rg=False, thresh=2.5, qs=0.01, qe=0.04, fix_qe=True, plot2d=True, logScale=True, clim=[1.e-3, 10.], debug=False): """ plot "merged" if no "subtracted" present """ if plot2d: plt.figure(figsize=(8, 10)) plt.subplot(211) else: plt.figure(figsize=(8, 6)) fh5, sn = self.process_sample_name(sn, debug=debug) ax1 = plt.gca() ax2 = ax1.twiny() ax3 = ax1.twinx() if 'subtracted' in self.d1s[sn].keys() and plot_merged == False: dkey = 'subtracted' elif 'merged' in self.d1s[sn].keys(): dkey = 'merged' else: raise Exception("processed data not present.") data = self.d1s[sn][dkey] #qgrid = data[0].qgrid ts = fh5[sn + '/primary/time'].value #idx = (qgrid>i_minq) & (qgrid<i_maxq) idx = (self.qgrid > i_minq) & (self.qgrid < i_maxq) data_t = [] data_i = [] data_rg = [] ds = [] frame_n = 0 for i in range(len(data)): ti = (ts[i] - ts[0]) / 60 if flowrate > 0: ti *= flowrate #if normalize_int: # data[i].set_trans(ref_trans=data[0].trans) ii = data[i].data[idx].sum() ds.append(data[i].data) if ii > thresh and calc_Rg and dkey == 'subtracted': i0, rg = dt.plot_Guinier(qs, qe, fix_qe=fix_qe, no_plot=True) #print("frame # %d: i0=%.2g, rg=%.2f" % (frame_n,i0,rg)) else: rg = 0 data_t.append(ti) data_i.append(ii) data_rg.append(rg) frame_n += 1 if ymin == -1: ymin = np.min(data_i) if ymax == -1: ymax = np.max(data_i) ax1.plot(data_i, 'b-') ax1.set_xlabel("frame #") ax1.set_xlim((0, len(data_i))) ax1.set_ylim(ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin)) ax1.set_ylabel("intensity") # read HPLC data directly from HDF5 hplc_grp = fh5[sn + "/hplc/data"] fields = lsh5(fh5[sn + '/hplc/data'], top_only=True, silent=True) dc = [] for fd in fields: dc = fh5[sn + '/hplc/data/' + fd].value.T ax2.plot(np.asarray(dc[0]) + offset, ymin + dc[1] / np.max(dc[1]) * (ymax - ymin) * uv_scale, label=fd) #ax2.set_ylim(0, np.max(dc[0][2])) if flowrate > 0: ax2.set_xlabel("volume (mL)") else: ax2.set_xlabel("time (minutes)") ax2.plot(data_t, data_i, 'bo', label='x-ray ROI') ax2.set_xlim((data_t[0], data_t[-1])) if showFWHM: half_max = (np.amax(data_i) - np.amin(data_i)) / 2 + np.amin(data_i) s = splrep(data_t, data_i - half_max) roots = sproot(s) fwhm = abs(roots[1] - roots[0]) print(roots[1], roots[0], half_max) if flowrate > 0: print("X-ray cell FWHMH =", fwhm, "ml") else: print("X-ray cell FWHMH =", fwhm, "min") ax2.plot([roots[0], roots[1]], [half_max, half_max], "k-|") if calc_Rg and dkey == 'subtracted': data_rg = np.asarray(data_rg) max_rg = np.max(data_rg) data_rg[data_rg == 0] = np.nan ax3.plot(data_rg, 'r.', label='rg') ax3.set_xlim((0, len(data_rg))) ax3.set_ylim((0, max_rg * 1.05)) ax3.set_ylabel("Rg") leg = ax2.legend(loc='upper left', fontsize=9, frameon=False) leg = ax3.legend(loc='center left', fontsize=9, frameon=False) if plot2d: plt.subplots_adjust(bottom=0.) plt.subplot(212) plt.subplots_adjust(top=1.) ax = plt.gca() ax.tick_params(axis='x', top=True) ax.xaxis.set_major_formatter(plt.NullFormatter()) #ax3 = ax1.twinx() d2 = np.vstack(ds).T + clim[0] / 2 #ext = [0, len(data), qgrid[-1], qgrid[0]] #asp = len(data)/qgrid[-1]/2 ext = [0, len(data), self.qgrid[-1], self.qgrid[0]] asp = len(data) / self.qgrid[-1] / 2 if logScale: plt.imshow(np.log(d2), extent=ext, aspect=asp) plt.clim(np.log(clim)) else: plt.imshow(d2, extent=ext, aspect=asp) plt.clim(clim) #plt.xlabel('frame #') plt.ylabel('q') #ax3.set_xlabel('frame #') plt.tight_layout() plt.show()
def gen_atsas_report(d1s, ax=None, fig=None, sn=None, skip=0, q_cutoff=0.6, print_results=True, path=""): if ax is None: ax = [] if fig is None: fig = plt.figure(figsize=(9, 3)) # rect = l, b, w, h ax.append(fig.add_axes([0.09, 0.25, 0.25, 0.6])) ax.append(fig.add_axes([0.41, 0.25, 0.25, 0.6])) ax.append(fig.add_axes([0.73, 0.25, 0.25, 0.6])) else: for a in ax: a.clear() if sn is None: tfn = "processed/t.dat" tfn_out = "processed/t.out" else: tfn = "processed/t.dat" tfn_out = f"processed/{sn}.out" atsas_create_temp_file(tfn, d1s, skip=skip, q_cutoff=q_cutoff) re_autorg = atsas_autorg(tfn, path=path) re_gnom = atsas_datgnom(tfn, re_autorg["Rg"], first=skip + 1, last=len(d1s.qgrid[d1s.qgrid <= q_cutoff]), fn_out=tfn_out, path=path) try: hdr, di, dq, dr, dpr, dpre = read_gnom_out_file(tfn_out) except: # this would happen if gnom fails to run hdr, di, dq, dr, dpr, dpre = 0, 0, 0, 0, 0, 0 idx = (d1s.qgrid < q_cutoff) ax[0].semilogy(di, dq) ax[0].errorbar(d1s.qgrid[idx], d1s.data[idx], d1s.err[idx]) #ax[0].yaxis.set_major_formatter(plt.NullFormatter()) #ax[0].set_title("intensity") ax[0].set_xlabel(r"$q$") if re_autorg["Rg"] > 0 and di is not None: axx = ax[0].twiny() Rg = re_autorg["Rg"] I0 = re_autorg["I0"] n1, n2 = re_autorg["fit range"] qf = d1s.qgrid[n1:n2] gf = I0 * np.exp(-(qf * Rg)**2 / 3) * 2 idx = (d1s.qgrid < 1.5 / re_autorg["Rg"]) axx.errorbar(d1s.qgrid[idx]**2, d1s.data[idx] * 2, d1s.err[idx], fmt="b.") axx.plot(qf * qf, gf, "k") axx.set_xlim(0, 3 * (1.5 / re_autorg["Rg"])**2) axx.set_xlabel(r"$q^2$", loc='right') locs = axx.get_xticks() #if len(locs>6): # locs = locs[::2] labels = [str(t) for t in locs] axx.set_xticks(locs[:-2]) axx.set_xticklabels(labels[:-2]) if re_autorg["Rg"] == 0: kratky_qm = 0.3 idx = (d1s.qgrid < kratky_qm) ax[1].plot(d1s.qgrid[idx], d1s.data[idx] * np.power(d1s.qgrid[idx], 2)) ax[1].set_xlabel(r"$q$") else: kratky_qm = 10. / re_autorg["Rg"] idx = (d1s.qgrid < kratky_qm) ax[1].plot(d1s.qgrid[idx] * re_autorg["Rg"], d1s.data[idx] * np.power(d1s.qgrid[idx], 2)) ax[1].set_xlabel(r"$q %times Rg$") ax[1].yaxis.set_major_formatter(plt.NullFormatter()) ax[1].set_title("kratky plot") ax[2].errorbar(dr, dpr, dpre) ax[2].yaxis.set_major_formatter(plt.NullFormatter()) ax[2].set_title(r"$P(r)$") ax[2].set_xlabel(r"$r$") ret = atsas_dat_tools(tfn_out, path=path) if print_results: print(f"Gunier fit: quality = {re_autorg['quality']} %,", end=" ") print(f"I0 = {re_autorg['I0']:.2f} +/- {re_autorg['I0 err']:.2f} , ", end="") print(f"Rg = {re_autorg['Rg']:.2f} +/- {re_autorg['Rg err']:.2f}") print( f"GNOM fit: quality = {re_gnom['quality']:.2f}, Dmax = {re_gnom['Dmax']:.2f}, Rg = {re_gnom['Rg (r)']:.2f}" ) print( f"Volume estimate: {ret['datporod']['vol']:.1f} (datporod), {ret['datmow']['vol']:.1f} (MoW)" ) print(f"MW estimate: {ret['datmow']['MW']/1000:.1f} kDa (MoW)") else: txt = f"Gunier fit: quality = {re_autorg['quality']} %, " txt += f"I0 = {re_autorg['I0']:.2f} +/- {re_autorg['I0 err']:.2f} , " txt += f"Rg = {re_autorg['Rg']:.2f} +/- {re_autorg['Rg err']:.2f}\n" txt += f"GNOM fit: quality = {re_gnom['quality']:.2f}, Dmax = {re_gnom['Dmax']:.2f}, Rg = {re_gnom['Rg (r)']:.2f}\n" txt += f"Volume estimate: {ret['datporod']['vol']:.1f} (datporod), {ret['datmow']['vol']:.1f} (MoW)\n" txt += f"MW estimate: {ret['datmow']['MW']/1000:.1f} kDa (MoW)" return txt
def plot_scatter_matrix(d, style='full', labels=None, fig=None, width_=6, **kwargs): """ Parameters ---------- width_ : float, optional Width for each subplot if no fig was provided """ n = len(d) if fig is None: fig = pl.figure(figsize=(width_ * n, width_ * n)) # predefine axes for the plots # 1st row -- histograms # next ones -- scatter plots axes = np.zeros(shape=(n, n), dtype=object) if style == 'upper_triang': # style with upper row -- hists # next -- upper triang only for r in xrange(n): for c in xrange(r, n): sp = pl.subplot(n, n, r * n + c + 1) axes[r, c] = pl.gca() for d1 in xrange(0, n - 1): for d2 in xrange(d1 + 1, n): # only upper triangle plot_scatter([d[i] for i in [d2, d1]], ax_scatter=axes[d1 + 1, d2], ax_hist_x=axes[0, d2] if d1 == 0 else None, ax_hist_y=None, bp_location='hist') elif style == 'full': nullfmt = pl.NullFormatter() # no labels # diagonal -- histograms for r in xrange(n): for c in xrange(n): sp = pl.subplot(n, n, r * n + c + 1) axes[r, c] = pl.gca() for d1 in xrange(0, n): # we should unify the ranges of values displayed ylim = np.min(d[d1]), np.max(d[d1]) for d2 in xrange(0, n): if d1 == d2: continue xlim = np.min(d[d2]), np.max(d[d2]) # only upper triangle hint_opacity = kwargs.pop('hint_opacity', 0.9) if (d1 == 0 and d2 == 1) else 0 plot_scatter([d[d2], d[d1]], ax_scatter=axes[d1, d2], ax_hist_x=axes[d2, d2] if (d2 == d1 + 1 or (d1 == 1 and d2 == 0)) else None, ax_hist_y=None, bp_location='hist', hint_opacity=hint_opacity, xlim=xlim, ylim=ylim, **kwargs) # adjust slightly if not (d2 == 0 or (d1 == 0 and d2 == 1) ): # not first column or in first row the first one # forget about y axis labels axes[d1, d2].yaxis.set_major_formatter(nullfmt) if not (d1 == n - 1 or (d2 == n - 1 and d1 == n - 2) ): # not first row or in first column in the first one # forget about y axis labels axes[d1, d2].xaxis.set_major_formatter(nullfmt) if not (labels in (None, [])): assert len(labels) == n, "We should be provided all needed labels" for d1, l in enumerate(labels): axes[d1, 0].set_ylabel(l) for d1, l in enumerate(labels): axes[n - 1, d1].set_xlabel(l) else: raise ValueError("Unknown style %s" % style) return fig, axes
def plot_scatter( dataXd, mask=None, masked_opacity=0., labels=None, colors=True, dimcolor=1, title=None, limits='auto', thresholds=None, hint_opacity=0.9, x_jitter=None, y_jitter=None, fig=None, ax_scatter=None, ax_hist_x=None, ax_hist_y=None, bp_location='scatter', xlim=None, ylim=None, rasterized=None, uniq=False, include_stats=False, ): """ Parameters ---------- dataXd: array The volumetric (or not) data to plot where first dimension should only have 2 items mask: array, optional Additional mask to specify which values do not consider to plot. By default values with 0s in both dimensions are not plotted. masked_opacity: float, optional By default masked out values are not plotted at all. Value in (0,1] will make them visible with this specified opacity labels: list of str, optional Labels to place for x and y axes colors: bool or string or colormap, optional Either to use colors to associate with physical location and what colormap to use (jet by default if colors=True) dimcolor: int If `colors`, then which dimension (within given 3D volume) to "track" limits: 'auto', 'same', 'per-axis' or (min, max) Limits for axes: when 'auto' if data ranges overlap is more than 50% of the union range, 'same' is considered. When 'same' -- the same limits on both axes as determined by data. If two-element tuple or list is provided, then that range is applied to both axes. hint_opacity: float, optional If `colors` is True, to then a "slice" of the volumetric data is plotted in the specified opacity to hint about the location of points in the original Xd data in `dimcolor` dimension x_jitter: float, optional Half-width of uniform noise added to x values. Might be useful if data is quantized so it is valuable to jitter points a bit. y_jitter: float, optional Half-width of uniform noise added to y values. Might be useful if data is quantized so it is valuable to jitter points a bit fig : Figure, optional Figure to plot on, otherwise new one created ax_*: axes, optional Axes for the scatter plot and histograms. If none of them is specified (which is the default) then 'classical' plot is rendered with histograms above and to the right bp_location: ('scatter', 'hist', None), optional Where to place boxplots depicting data range xlim: tuple, optional ylim: tuple, optional To fix plotted range rasterized: bool, optional Passed to scatter call, to allow rasterization of heavy scatter plots uniq: bool, optional Plot uniq values (those present in one but not in the other) along each axis with crosses include_stats: bool, optional Whether to report additional statistics on the data. Stats are also reported via verbose at level 2 """ if len(dataXd) != 2: raise ValueError("First axis of dataXd can only have two dimensions, " "got {0}".format(len(dataXd))) dataXd = np.asanyarray( dataXd ) # TODO: allow to operate on list of arrays to not waste RAM/cycles data = dataXd.reshape((2, -1)) if dataXd.ndim < 5: ntimepoints = 1 elif dataXd.ndim == 5: ntimepoints = dataXd.shape[-1] else: raise ValueError("Do not know how to handle data with %d dimensions" % (dataXd.ndim - 1)) if x_jitter or y_jitter: data = data.copy() # lazy and wasteful def jitter_me(x, w): x += np.random.uniform(-w, w, size=data.shape[-1]) if x_jitter: jitter_me(data[0, :], x_jitter) if y_jitter: jitter_me(data[1, :], y_jitter) finites = np.isfinite(data) nz = np.logical_and(data != 0, finites) # TODO : avoid doing data !=0 and just use provided utter mask #nz[:, 80000:] = False # for quick testing nzsum = np.sum(nz, axis=0) intersection = nzsum == 2 # for coloring we would need to know all the indices union = nzsum > 0 x, y = datainter = data[:, intersection] if mask is not None: if mask.size * ntimepoints == intersection.size: # we have got a single mask applicable to both x and y pass elif mask.size * ntimepoints == 2 * intersection.size: # we have got a mask per each, let's get an intersection assert mask.shape[0] == 2, "had to get 1 for x, 1 for y" mask = np.logical_and(mask[0], mask[1]) else: raise ValueError( "mask of shape %s. data of shape %s. ntimepoints=%d. " "Teach me how to apply it" % (mask.shape, data.shape, ntimepoints)) # replicate mask ntimepoints times mask = np.repeat(mask.ravel(), ntimepoints)[intersection] != 0 x_masked = x[mask] y_masked = y[mask] xnoty = (nz[0].astype(int) - nz[1].astype(int)) > 0 ynotx = (nz[1].astype(int) - nz[0].astype(int)) > 0 msg = '' if not np.all(finites): msg = " non-finite x: %d, y: %d" % (np.sum(~finites[0]), np.sum(~finites[1])) verbose( 1, "total: %d union: %d%s intersection: %d x_only: %d y_only: %d%s" % (len(nzsum), np.sum(union), mask is not None and ' masked: %d' % np.sum(mask) or '', np.sum(intersection), np.sum(xnoty), np.sum(ynotx), msg)) if include_stats: # report some statistics as well import scipy.stats as ss r, p = ss.pearsonr(x, y) d = np.linalg.norm(x - y) statsline = "r=%.2f p=%.4g ||x-y||=%.4g" % (r, p, d) try: from mvpa2.misc.dcov import dcorcoef nmax = min(1000, len(x)) idx = np.random.permutation(np.arange(len(x)))[:nmax] dcor = dcorcoef(x[idx], y[idx]) dcor_s = '' if len(x) == nmax else '[%d random]' % nmax statsline += ' dcorr%s=%.4g' % (dcor_s, dcor) except ImportError: pass verbose(2, statsline) else: statsline = '' #fig=pl.figure() #pl.plot(datainter[0], datainter[1], '.') #fig.show() nullfmt = pl.NullFormatter() # no labels # definitions for the axes left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 if not (bool(ax_scatter) or bool(ax_hist_x) or bool(ax_hist_y)): # no custom axes specified # our default setup rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] # start with a rectangular Figure if fig is None: fig = pl.figure(figsize=(10, 10)) ax_scatter = pl.axes(rect_scatter) ax_hist_x = pl.axes(rect_histx) ax_hist_y = pl.axes(rect_histy) else: # check if all not None? # assert(len(axes) == 3) ax_bp_x, ax_bp_y = None, None if ax_scatter is None: raise ValueError("Makes no sense to do not have scatter plot") ax_bp_x = ax_bp_y = None if bp_location is not None: ax_bp_x_parent = ax_bp_y_parent = None if bp_location == 'scatter': # place boxplots into histogram plots ax_bp_x_parent = ax_scatter ax_bp_y_parent = ax_scatter elif bp_location == 'hist': ax_bp_x_parent = ax_hist_x ax_bp_y_parent = ax_hist_y else: raise ValueError( "bp_location needs to be from (None, 'scatter', 'hist')") if ax_bp_x_parent: hist_x_pos = ax_bp_x_parent.get_position() ax_bp_x = pl_axes([ hist_x_pos.x0, hist_x_pos.y0 + hist_x_pos.height * 0.9, hist_x_pos.width, hist_x_pos.height * 0.1 ], facecolor='y') if ax_bp_y_parent: hist_y_pos = ax_bp_y_parent.get_position() ax_bp_y = pl_axes([ hist_y_pos.x0 + hist_y_pos.width * 0.9, hist_y_pos.y0, hist_y_pos.width * 0.1, hist_y_pos.height ], facecolor='y') # ax_bp_y = pl_axes( [left + width * 0.9, bottom, width/10, height], facecolor='y' ) if ax_hist_y else None sc_kwargs = dict(facecolors='none', s=1, rasterized=rasterized) # common kwargs # let's use colormap to get non-boring colors cm = colors # e.g. if it is None if colors is True: cm = pl.matplotlib.cm.get_cmap('jet') elif isinstance(colors, str): cm = pl.matplotlib.cm.get_cmap(colors) if cm and len(dataXd.shape) > dimcolor + 1: cm.set_under((1, 1, 1, 0.1)) # transparent what is not in range # we need to get our indices back for those we are going to plot. probably this is the least efficient way: ndindices_all = np.array(list(np.ndindex(dataXd.shape[1:]))) ndindices_nz = ndindices_all[intersection] # choose color based on dimcolor dimcolor_len = float(dataXd.shape[1 + dimcolor]) edgecolors = cm(((cm.N - 1) * ndindices_nz[:, dimcolor] / dimcolor_len).astype(int)) if mask is not None: # Plot first those which might be masked out if masked_opacity: mask_inv = np.logical_not(mask) mask_edgecolors = edgecolors[mask_inv].copy() # Adjust alpha value mask_edgecolors[:, -1] *= masked_opacity ax_scatter.scatter(x[mask_inv], y[mask_inv], edgecolors=mask_edgecolors, alpha=masked_opacity, **sc_kwargs) # Plot (on top) those which are not masked-out if mask.size: x_plot, y_plot, edgecolors_plot = x[mask], y[mask], edgecolors[ mask] else: # older numpys blow here x_plot, y_plot, edgecolors_plot = (np.array([]), ) * 3 else: # Just plot all of them at once x_plot, y_plot, edgecolors_plot = x, y, edgecolors if len(x_plot): ax_scatter.scatter(x_plot, y_plot, edgecolors=edgecolors_plot, **sc_kwargs) # for orientation we need to plot 1 slice... assume that the last dimension is z -- figure out a slice with max # of non-zeros zdim_entries = ndindices_nz[:, -1] if np.size(zdim_entries): zdim_counts, _ = np.histogram(zdim_entries, bins=np.arange( 0, np.max(zdim_entries) + 1)) zdim_max = np.argmax(zdim_counts) if hint_opacity: # now we need to plot that zdim_max slice taking into account our colormap # create new axes axslice = pl_axes( [left, bottom + height * 0.72, width / 4., height / 5.], facecolor='y') axslice.axis('off') sslice = np.zeros(dataXd.shape[1:3] ) # XXX hardcoded assumption on dimcolor =1 sslice[:, :] = np.arange(dimcolor_len)[None, :] # if there is time dimension -- choose minimal value across all values dataXd_mint = np.min(dataXd, axis=-1) if dataXd.ndim == 5 else dataXd sslice[ dataXd_mint[0, ..., zdim_max] == 0] = -1 # reset those not in the picture to be "under" range axslice.imshow(sslice, alpha=hint_opacity, cmap=cm) else: # the scatter plot without colors to distinguish location ax_scatter.scatter(x, y, **sc_kwargs) if labels: ax_scatter.set_xlabel(labels[0]) ax_scatter.set_ylabel(labels[1]) # "unique" points on each of the axes if uniq: if np.sum(xnoty): ax_scatter.scatter(fill_nonfinites(data[0, np.where(xnoty)[0]]), fill_nonfinites(data[1, np.where(xnoty)[0]]), edgecolor='b', **sc_kwargs) if np.sum(ynotx): ax_scatter.scatter(fill_nonfinites(data[0, np.where(ynotx)[0]]), fill_nonfinites(data[1, np.where(ynotx)[0]]), edgecolor='g', **sc_kwargs) # Axes if np.size(x): ax_scatter.plot((np.min(x), np.max(x)), (0, 0), 'r', alpha=0.5) else: warning("There is nothing to plot, returning early") return pl.gcf() ax_scatter.plot((0, 0), (np.min(y), np.max(y)), 'r', alpha=0.5) if (mask is not None and not masked_opacity and np.sum(mask)): # if there is a non-degenerate mask which was not intended to be plotted, # take those values away while estimating min/max range _ = x[mask] minx, maxx = np.min(_), np.max(_) _ = y[mask] miny, maxy = np.min(_), np.max(_) del _ # no need to consume RAM # print "Here y range", miny, maxy else: minx, maxx = np.min(x), np.max(x) miny, maxy = np.min(y), np.max(y) # Process 'limits' option if isinstance(limits, str): limits = limits.lower() if limits == 'auto': overlap = min(maxx, maxy) - max(minx, miny) range_ = max(maxx, maxy) - min(minx, miny) limits = { True: 'same', False: 'per-axis' }[not range_ or overlap / float(range_) > 0.5] if limits == 'per-axis': same_range = False if xlim is None: # add some white border dx = (maxx - minx) / 20. xlim = (minx - dx, maxx + dx) if ylim is None: dy = (maxy - miny) / 20. ylim = (miny - dy, maxy + dy) elif limits == 'same': same_range = True # assign limits the numerical range limits = (np.min([minx, miny]), np.max([maxx, maxy])) else: raise ValueError("Do not know how to handle same_range=%r" % (limits, )) else: same_range = True # Let's now plot threshold lines if provided if thresholds is not None: stylekwargs = dict(colors='k', linestyles='dotted') if len(thresholds): ax_scatter.vlines(thresholds[0], ax_scatter.get_xlim()[0] * 0.9, ax_scatter.get_xlim()[1] * 0.9, **stylekwargs) if len(thresholds) > 1: ax_scatter.hlines(thresholds[1], ax_scatter.get_ylim()[0] * 0.9, ax_scatter.get_ylim()[1] * 0.9, **stylekwargs) if same_range: # now determine nice limits by hand: binwidthx = binwidthy = binwidth = np.max(datainter) / 51. # 0.25 minxy, maxxy = limits sgn = np.sign(minxy) xyrange = maxxy - minxy xyamax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) limn = sgn * (int(sgn * minxy / binwidth) - sgn) * binwidth limp = (int(maxxy / binwidth) + 1) * binwidth ax_scatter.plot((limn * 0.9, limp * 0.9), (limn * 0.9, limp * 0.9), 'y--') if xlim is None: xlim = (limn, limp) if ylim is None: ylim = (limn, limp) binsx = binsy = bins = np.arange(limn, limp + binwidth, binwidth) else: binwidthx = (maxx - minx) / 51. binwidthy = (maxy - miny) / 51. try: binsx = np.arange(minx, maxx + binwidthx, binwidthx) binsy = np.arange(miny, maxy + binwidthy, binwidthy) except Exception as exc: warning( "Received following exception while trying to get bins for " "minx=%(minx)f maxx=%(maxx)f binwidthx=%(binwidthx)s " "miny=%(miny)f maxy=%(maxy)f binwidthy=%(binwidthy)s: %(exc)s. " "Returning early" % locals()) return pl.gcf() if xlim is not None: ax_scatter.set_xlim(xlim) if ylim is not None: ax_scatter.set_ylim(ylim) # get values to plot for histogram and boxplot x_hist, y_hist = (x, y) if (mask is None or not np.sum(mask)) else (x_masked, y_masked) if np.any(binsx) and ax_hist_x is not None: ax_hist_x.xaxis.set_major_formatter(nullfmt) histx = ax_hist_x.hist(x_hist, bins=binsx, facecolor='b') ax_hist_x.set_xlim(ax_scatter.get_xlim()) ax_hist_x.vlines(0, 0, 0.9 * np.max(histx[0]), 'r') if np.any(binsy) and ax_hist_y is not None: ax_hist_y.yaxis.set_major_formatter(nullfmt) histy = ax_hist_y.hist(y_hist, bins=binsy, orientation='horizontal', facecolor='g') ax_hist_y.set_ylim(ax_scatter.get_ylim()) ax_hist_y.hlines(0, 0, 0.9 * np.max(histy[0]), 'r') rect_scatter = [left, bottom, width, height] # Box plots if ax_bp_x is not None: ax_bp_x.axis('off') bpx = ax_bp_x.boxplot(x_hist, vert=0) #'r', 0) ax_bp_x.set_xlim(ax_scatter.get_xlim()) if ax_bp_y is not None: ax_bp_y.axis('off') bpy = ax_bp_y.boxplot(y_hist, sym='g+') ax_bp_y.set_ylim(ax_scatter.get_ylim()) if statsline: # draw the text based on gca y1, y2 = ax_scatter.get_ylim() x1, x2 = ax_scatter.get_xlim() ax_scatter.text( 0.5 * (x1 + x2), # center y2 - 0.02 * (y2 - y1), statsline, verticalalignment="top", horizontalalignment="center") if title: pl.title(title) return pl.gcf()
def graph(self, outfmt, filename=None): def wrap(title): if title: return textwrap.fill(title, 30) def _graph(ax, dates, legend=True): ax.xaxis.set_ticks(ticks) pylab.setp(ax.xaxis.get_ticklabels(), rotation=90, fontsize=8) ax.xaxis.set_major_formatter(pylab.FixedFormatter(tick_labels)) ylocator = pylab.MaxNLocator(10, steps=[1,2,5,10],integer=1) ax.yaxis.set_major_locator(ylocator) ax.yaxis.grid(1) if self.stack: bottom = pylab.zeros(self.n_bins) legend_handles = [] legend_labels = [] strata_bins = self.strata_date_bin(dates, self.stack) if self.stack_ratios: strata_bins = self.strata_ratios(strata_bins) for n, (v, l) in enumerate(self.stack.order_labels): if self.stack_suppress and v in self.stack_suppress: continue bins = strata_bins[(v,)] handles = pylab.bar(x, bins, bottom=bottom, width=1.0, align='center', color=colors[n]) legend_handles.append(handles[0]) legend_labels.append(wrap(l)) bottom += bins if legend: l = pylab.legend(legend_handles, legend_labels, loc=0, prop=dict(size=8), title=wrap(self.stack_label)) pylab.setp(l.get_title(), fontsize=9) # pylab.setp(l.get_texts(), fontsize=8) if self.stack_ratios: ax.set_ylim(0, 100) else: bins = self.date_bin(dates) pylab.bar(x, bins, width=1.0, color='#bbbbff', align='center') pad_axis(ax, 'x') pad_axis(ax, 'y') ticks, tick_labels = self.calc_tick_labels() x = pylab.arange(self.n_bins) pylab.figure(figsize=(10,6), dpi=100, facecolor='w') colors = None ylabel = 'Count' if self.stack: colors = trafficlight.make_n_colors(len(self.stack.order)) if self.stack_ratios: ylabel = 'Ratio' if self.lower_dates: lax = pylab.axes([0.1, 0.2, .8, 0.34], frameon=False) _graph(lax, self.lower_dates, False) pylab.ylabel(wrap(self.lower_date_label + ' ' + ylabel), fontsize=9) ax = pylab.axes([0.1, 0.58, .8, 0.34], frameon=False) _graph(ax, self.dates) ax.xaxis.set_major_formatter(pylab.NullFormatter()) pylab.ylabel(wrap(self.date_label + ' ' + ylabel), fontsize=9) same_scale('x', lax, ax) #same_scale('y', lax, ax) else: ax = pylab.axes([0.1, 0.2, .8, 0.7], frameon=False) _graph(ax, self.dates) pylab.ylabel(ylabel, fontsize=9) if self.date_label is not None: pylab.xlabel(self.date_label) if self.title: pylab.title(self.title) if not filename: outfn = utils.randfn('vis', outfmt) filename = os.path.join(config.scratchdir, outfn) else: outfn = filename pylab.savefig(filename) return outfn
def plot(x, y, x_label="", y_label="", col=True, x_log=False, y_log=False, names=None, graph_name=None, legend_name=None, xyline=True, disable_x_tics=False, no_scatter=False, nosymbols=False, symbol_list=False, makesquare=False, y1line=False, yerr=None, minX=False, minY=False, maxX=False, maxY=False): try: import pylab except: print("Error: pylab not available. Plotting features will not work.") return #pylab.rcParams.update(params_onecolumn) pylab.rcParams.update(params_twocolumn) if x[0].__class__ != list: x = [x] y = [y] if yerr: yerr = [yerr] global SYMBOLS if symbol_list: SYMBOLS = symbol_list if not col: if len(x) > len(SYMBOLS): print("Warning: Too many types (%d) for only %d symbols." % (len(x), len(SYMBOLS))) return else: if len(x) > len(COLOURS): print("Warning: Too many types (%d) for only %d colours." % (len(x), len(COLOURS))) return pylab.figure(1) pylab.clf() if disable_x_tics: if y_log: ax = pylab.axes([0.17, 0.14, 0.95 - 0.17, 0.95 - 0.14 ]) # Use this when 10^-1 kicks out the y-label else: ax = pylab.axes([0.14, 0.14, 0.95 - 0.14, 0.95 - 0.14]) else: if y_log: ax = pylab.axes([0.17, 0.22, 0.95 - 0.17, 0.95 - 0.22]) else: ax = pylab.axes([0.14, 0.2, 0.95 - 0.14, 0.95 - 0.2]) if x_log: ax.set_xscale('log') if y_log: ax.set_yscale('log') # Plot BOT_NUMS = [99999.0, 99999.0] TOP_NUMS = [0.0, 0.0] handles = [] xy_line_col = 'b' if yerr: plot_func = ax.errorbar plot_args = lambda i: {'yerr': yerr[i]} else: plot_func = ax.plot plot_args = lambda i: {} for i in range(len(x)): if col: if no_scatter: if nosymbols: handles.append( plot_func(x[i], y[i], c=COLOURS[i], **plot_args(i))) else: handles.append( plot_func(x[i], y[i], c=COLOURS[i], marker=SYMBOLS[i], **plot_args(i))) else: handles.append( ax.scatter(x[i], y[i], s=40, c=COLOURS[i], marker=SYMBOLS[i])) else: xy_line_col = 'k' if no_scatter: if nosymbols: handles.append(plot_func(x[i], y[i], c='k', **plot_args(i))) else: handles.append( plot_func(x[i], y[i], c='k', marker=SYMBOLS[i], **plot_args(i))) else: handles.append( ax.scatter(x[i], y[i], s=40, c='k', marker=SYMBOLS[i])) if TOP_NUMS[0] < max(x[i]): TOP_NUMS[0] = max(x[i]) if TOP_NUMS[1] < max(y[i]): TOP_NUMS[1] = max(y[i]) if BOT_NUMS[0] > min(x[i]): BOT_NUMS[0] = min(x[i]) if BOT_NUMS[1] > min(y[i]): BOT_NUMS[1] = min(y[i]) DELTA = [(TOP_NUMS[0] - BOT_NUMS[0]) * 0.05, (TOP_NUMS[1] - BOT_NUMS[1]) * 0.05] if x_log: BOT_X = BOT_NUMS[0] / 2 TOP_X = TOP_NUMS[0] * 2 else: BOT_X = BOT_NUMS[0] - DELTA[0] TOP_X = TOP_NUMS[0] + DELTA[0] if y_log: BOT_Y = BOT_NUMS[1] / 2 TOP_Y = TOP_NUMS[1] * 2 else: BOT_Y = BOT_NUMS[1] - DELTA[1] TOP_Y = TOP_NUMS[1] + DELTA[1] if makesquare: TOP_Y = max(TOP_Y, TOP_X) TOP_X = max(TOP_Y, TOP_X) BOT_X = min(BOT_X, BOT_Y) BOT_Y = min(BOT_X, BOT_Y) if maxX: TOP_X = maxX if maxY: TOP_Y = maxY if minX: BOT_X = minX if minY: BOT_Y = minY if xyline: ax.plot([min([BOT_X, BOT_Y]), max([TOP_X, TOP_Y])], [min([BOT_X, BOT_Y]), max([TOP_X, TOP_Y])], c=xy_line_col) if y1line: ax.plot([min([BOT_X, BOT_Y]), max([TOP_X, TOP_Y])], [1.0, 1.0], c=xy_line_col) ax.set_xlim(BOT_X, TOP_X) #ax.set_xlim(BOT_NUMS[0], TOP_NUMS[0]) ax.set_ylim(BOT_Y, TOP_Y) #pylab.xlabel("\\textbf{%s}" % x_label) #pylab.ylabel("\\textbf{%s}" % y_label) pylab.xlabel(x_label) pylab.ylabel(y_label) if names: if no_scatter: handles = [h[0] for h in handles] if legend_name: pylab.legend(handles, names, loc="best", title=legend_name) else: pylab.legend(handles, names, loc="best") if graph_name: pylab.title(graph_name) if disable_x_tics: ax.xaxis.set_major_formatter(pylab.NullFormatter()) pylab.show()
cax = divider.append_axes("right", size="5%", pad=0.05) cbar = pl.colorbar(im, cax=cax, ticks=[0, 0.5, 1]) cbar.ax.tick_params(labelsize=18) # load image : logo = Image.open("graph.png") image_axis.imshow(logo, clip_box=bbox, aspect='equal', origin='lower', interpolation='nearest') # TEXT matplotlib ax4.text(-0.1, 0.85, "(d)", fontsize=fontsize+2, transform=ax4.transAxes) # color by value from a chosen colormap n = 20 colors = pl.cm.brg(np.linspace(0, 1, n)) for i in range(n): pl.plot(x, i*y, color=colors[i]) nodes = [] a = [0] for i in range(n_comm): a.append(a[i]+len_communities[i]) nodes.append(range(a[i], a[i+1])) # remove labels ax5.xaxis.set_major_formatter(pl.NullFormatter())
def plot_BD(NU, DATA, covariates, covnames, signals=None, drift=[offset, l, q]): # Prepare figure fig = plt.figure(figsize=(10, 5)) fig.subplots_adjust(left=0.05, right=0.95, wspace=0.5) ax1 = plt.subplot2grid((3, 5), (0, 0), colspan=2) ax2 = plt.subplot2grid((3, 5), (1, 0), colspan=2) ax3 = plt.subplot2grid((3, 5), (2, 0), colspan=2) axs = [ax1, ax2, ax3] # Run only with offset for each instrument POW, S, PAR, RR = periodogram(NU, DATA, FF0=[ offset, ], covariates=signals) maxpow = POW.max() maxax = ax1 ax1.semilogx(1 / NU, POW, label='GLS', color='0.5') # Run with offset and linear drift POW, S, PAR, RR = periodogram(NU, DATA, FF0=drift, covariates=signals) ax2.semilogx(1 / NU, POW, label='GLS + drift', color='0.25') if maxpow < POW.max(): maxax = POW.max() maxax = ax2 # Add signals as covariates if signals is not None: for inst in range(len(covariates)): covariates[inst] = np.concatenate( [covariates[inst], signals[inst]]) covnames.extend(['cos1', 'sin1']) # Run with offset, linear drift and covariates POW, S, PAR, RR = periodogram(NU, DATA, FF0=drift, covariates=covariates) label = 'GLS + drift + ' + '{} + ' * (len(covnames) - 1) + '{}' ax3.semilogx(1 / NU, POW, label=label.format(*covnames), color='0.1') ax3.set_xlabel('Period [d]') if maxpow < POW.max(): maxax = POW.max() maxax = ax3 # Find highestpeak in full model maxper = 1 / NU[np.argmax(POW)] # Make plot of covariates for i in range(len(covnames)): print(i, covnames[i]) # Plot periodogram and histogram of covariate power ax = plt.subplot2grid((len(covnames), 5), (i, 2), colspan=2) ax.semilogx(1 / NU, PAR[:, len(drift) + i], color='C{}'.format(i + 2), label=covnames[i].upper()) axh = plt.subplot2grid((len(covnames), 5), (i, 4)) axh.hist(PAR[:, len(drift) + i], 100, color='C{}'.format(i + 2), label=covnames[i]) # Remove ticks in histogram axh.yaxis.set_major_formatter(plt.NullFormatter()) ax.legend(loc=0) ax.axvline(maxper, ls=':', color='r') if i == len(covnames) - 1: ax.set_xlabel('Period [d]') # Annotate maximum period # maxax.annotate(s='{:.2f} d'.format(maxper), xy=(maxper, maxpow)) # Decorate plots. # Maximum period, legend, and align vertical axis of periodograms. for ax in axs: ax.axvline(maxper, ls=':', color='r') ax.legend(loc=0, fontsize=8) ax.set_ylim(maxax.get_ylim()) if ax != axs[-1]: ax.xaxis.set_major_formatter(plt.NullFormatter()) # Figure title title = '{:.2f} d'.format(maxper) fig.text(0.5, 0.95, title, va='center', ha='center', fontsize=16) return fig, maxper
handles1.append(ax1.plot(xs[i], sizes[i], c=COLOURS[i], ls=LINES[i])) handles2.append(ax2.plot(xs[i], times[i], c=COLOURS[i], ls=LINES[i])) #handles1.append(ax1.scatter(xs[i], sizes[i], c=COLOURS[i], marker=SYMBOLS[i])) #handles2.append(ax2.scatter(xs[i], times[i], c=COLOURS[i], marker=SYMBOLS[i])) ax1.legend(dom_names, loc="upper left") #ax = pylab.axes([0.17,0.22,0.95-0.17,0.95-0.22]) ax2.set_yscale('log') pylab.xlabel('Problem') ax1.set_ylabel('Policy Size') ax2.set_ylabel('Runtime (s)') ax1.xaxis.set_major_formatter( pylab.NullFormatter() ) ax2.xaxis.set_major_formatter( pylab.NullFormatter() ) #ax1.plot(x, y) #ax1.set_title('Sharing both axes') #ax2.scatter(x, y) #ax3.scatter(x, 2 * y ** 2 - 1, color='r') # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0,left=0.2,top=0.95,right=0.96) pylab.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) ax2.yaxis.get_major_ticks()[-1].label1.set_visible(False) pylab.show()