def plotData(self): plt.figure(self._name) plt.axes(self._ax1) channels = self._cd.getChannelsByKind(ChannelsEnum.GAIT_PHASE) # get the four gait phase channels for c in channels: if c.target == TargetsEnum.LEFT_HIND: self.channelLH = c elif c.target == TargetsEnum.LEFT_FORE: self.channelLF = c elif c.target == TargetsEnum.RIGHT_FORE: self.channelRF = c elif c.target == TargetsEnum.RIGHT_HIND: self.channelRH = c else: raise Exception, "Unknown Channel Target: " + str(c.target) prevKey = self.channelLF.keys[0] startTime = prevKey.time stopTime = self.channelLF.keys[-1].time for key in self.channelRF.keys[1:]: self._ax1.plot([prevKey.time, key.time], [PlotTest.LH, PlotTest.LH], linewidth=10, color=self.mapValueToColor(prevKey.value)) prevKey = key rect = self._ax1.patch rect.set_facecolor(PlotTest.BACKGROUND_COLOR) plt.xlim([startTime, stopTime]) plt.show()
def swi_histogram(self,dir,name,measure,dpi=80,width=8,height=6,b_left='0.1',b_bot='0.1',b_top='0.1',b_right='0.1',bins='20'): s=ccm.stats.Stats('%s/%s'%(dir,name)) data=s.get_raw(measure) bins=int(bins) pylab.figure(figsize=(float(width),float(height))) try: b_left=float(b_left) except: b_left=0.1 try: b_right=float(b_right) except: b_right=0.1 try: b_top=float(b_top) except: b_top=0.1 try: b_bot=float(b_bot) except: b_bot=0.1 pylab.axes((b_left,b_bot,1.0-b_left-b_right,1.0-b_top-b_bot)) pylab.hist(data,bins=bins) img=StringIO.StringIO() if type(dpi) is list: dpi=dpi[-1] pylab.savefig(img,dpi=int(dpi),format='png') return 'image/png',img.getvalue()
def PlotNCodonMuts(allmutations, plotfile, title): """Plots number of nucleotide changes per codon mutation. allmutations -> list of all mutations as tuples (wtcodon, r, mutcodon) plotfile -> name of the plot file we create. title -> string giving the plot title. """ pylab.figure(figsize=(3.5, 2.25)) (lmargin, rmargin, bmargin, tmargin) = (0.16, 0.01, 0.21, 0.07) pylab.axes([lmargin, bmargin, 1.0 - lmargin - rmargin, 1.0 - bmargin - tmargin]) nchanges = {1:0, 2:0, 3:0} nmuts = len(allmutations) for (wtcodon, r, mutcodon) in allmutations: assert 3 == len(wtcodon) == len(mutcodon) diffs = len([i for i in range(3) if wtcodon[i] != mutcodon[i]]) nchanges[diffs] += 1 barwidth = 0.6 xs = [1, 2, 3] nactual = [nchanges[x] for x in xs] nexpected = [nmuts * 9. / 63., nmuts * 27. / 63., nmuts * 27. / 63.] bar = pylab.bar([x - barwidth / 2.0 for x in xs], nactual, width=barwidth) pred = pylab.plot(xs, nexpected, 'rx', markersize=6, mew=3) pylab.gca().set_xlim([0.5, 3.5]) pylab.gca().set_ylim([0, max(nactual + nexpected) * 1.1]) pylab.gca().xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(4)) pylab.gca().yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(5)) pylab.xlabel('nucleotide changes in codon') pylab.ylabel('number of mutations') pylab.legend((bar[0], pred[0]), ('actual', 'expected'), loc='upper left', numpoints=1, handlelength=0.9, borderaxespad=0, handletextpad=0.4) pylab.title(title, fontsize=12) pylab.savefig(plotfile) time.sleep(0.5) pylab.show()
def _example_matplotlib_plot(): import pylab from pylab import arange, pi, sin, cos, sqrt # Generate data x = arange(-2 * pi, 2 * pi, 0.01) y1 = sin(x) y2 = cos(x) # Plot data pylab.ioff() # print 'Plotting data' pylab.figure(1) pylab.clf() # print 'Setting axes' pylab.axes([0.125, 0.2, 0.95 - 0.125, 0.95 - 0.2]) # print 'Plotting' pylab.plot(x, y1, "g:", label="sin(x)") pylab.plot(x, y2, "-b", label="cos(x)") # print 'Labelling' pylab.xlabel("x (radians)") pylab.ylabel("y") pylab.legend() print "Saving to fig1.eps" pylab.savefig("fig1.eps") pylab.ion()
def create_pie_chart(self, snapshot, filename=''): """ Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`. """ try: from pylab import figure, title, pie, axes, savefig from pylab import sum as pylab_sum except ImportError: return self.nopylab_msg % ("pie_chart") # Don't bother illustrating a pie without pieces. if not snapshot.tracked_total: return '' classlist = [] sizelist = [] for k, v in list(snapshot.classes.items()): if v['pct'] > 3.0: classlist.append(k) sizelist.append(v['sum']) sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist)) classlist.insert(0, 'Other') #sizelist = [x*0.01 for x in sizelist] title("Snapshot (%s) Memory Distribution" % (snapshot.desc)) figure(figsize=(8, 8)) axes([0.1, 0.1, 0.8, 0.8]) pie(sizelist, labels=classlist) savefig(filename, dpi=50) return self.chart_tag % (self.relative_path(filename))
def field_map_ndar(ndar_field,t,ar_coorx,ar_coory,X,image_out,variable): ar_field=ndar_field[t,:] max_val=int(np.max(ndar_field)) if variable==4: max_val=100. xmin=min(ar_coorx);xmax=max(ar_coorx) ymin=min(ar_coory);ymax=max(ar_coory) step=X nx=(xmax-xmin)/step+1 ny=(ymax-ymin)/step+1 ar_indx=np.array((ar_coorx-xmin)/step,int) ar_indy=np.array((ar_coory-ymin)/step,int) ar_map=np.ones((ny,nx))*-99.9 ar_map[ar_indy,ar_indx]=ar_field ar_map2 = M.masked_where(ar_map <0, ar_map) ut.check_file_exist(image_out) pl.clf() pl.axes(axisbg='gray') pl.imshow(ar_map2, cmap=pl.cm.RdBu, interpolation='Nearest', origin='lower', vmax=max_val, vmin=0) pl.title('time step= '+ut.string(t,len(str(t)))) pl.colorbar() pl.savefig(image_out)
def newFigLayer(): pylab.clf() pylab.figure(figsize=(8, 8)) pylab.axes([0.15, 0.15, 0.8, 0.81]) pylab.axis([0.6, -0.4, -0.4, 0.6]) pylab.xlabel(r"$\Delta$\textsf{RA from Sgr A* (arcsec)}") pylab.ylabel(r"$\Delta$\textsf{Dec. from Sgr A* (arcsec)}")
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True): """ Capture a screeshot of the Mayavi figure and display it in the matplotlib axes. """ import pylab as pl # Late import to avoid triggering wx imports before needed. try: from mayavi import mlab except ImportError: # Try out old install of Mayavi, with namespace packages from enthought.mayavi import mlab if mayavi_fig is None: mayavi_fig = mlab.gcf() else: mlab.figure(mayavi_fig) if mpl_axes is not None: pl.axes(mpl_axes) filename = tempfile.mktemp('.png') mlab.savefig(filename, figure=mayavi_fig) image3d = pl.imread(filename) if autocrop: bg_color = mayavi_fig.scene.background image3d = autocrop_img(image3d, bg_color) pl.imshow(image3d) pl.axis('off') os.unlink(filename)
def test_varying_inclination(self): #""" Test that the waveform is consistent for changes in inclination #""" sigmas = [] incs = numpy.arange(0, 21, 1.0) * lal.PI / 10.0 for inc in incs: # WARNING: This does not properly handle the case of SpinTaylor* # where the spin orientation is not relative to the inclination hp, hc = get_waveform(self.p, inclination=inc) s = sigma(hp, low_frequency_cutoff=self.p.f_lower) sigmas.append(s) f = pylab.figure() pylab.axes([.1, .2, 0.8, 0.70]) pylab.plot(incs, sigmas) pylab.title("Vary %s inclination, $\\tilde{h}$+" % self.p.approximant) pylab.xlabel("Inclination (radians)") pylab.ylabel("sigma (flat PSD)") info = self.version_txt pylab.figtext(0.05, 0.05, info) if self.save_plots: pname = self.plot_dir + "/%s-vary-inclination.png" % self.p.approximant pylab.savefig(pname) if self.show_plots: pylab.show() else: pylab.close(f) self.assertAlmostEqual(sigmas[-1], sigmas[0], places=7) self.assertAlmostEqual(max(sigmas), sigmas[0], places=7) self.assertTrue(sigmas[0] > sigmas[5])
def __init__(self, cut_coords, axes=None): """ Create 3 linked axes for plotting orthogonal cuts. Parameters ---------- cut_coords: 3 tuple of ints The cut position, in world space. axes: matplotlib axes object, optional The axes that will be subdivided in 3. """ self._cut_coords = cut_coords if axes is None: axes = pl.axes((0., 0., 1., 1.)) axes.axis('off') self.frame_axes = axes axes.set_zorder(1) bb = axes.get_position() self.rect = (bb.x0, bb.y0, bb.x1, bb.y1) self._object_bounds = dict() # Create our axes: self.axes = dict() for index, name in enumerate(('x', 'y', 'z')): ax = pl.axes([0.3*index, 0, .3, 1]) ax.axis('off') self.axes[name] = ax ax.set_axes_locator(self._locator) self._object_bounds[ax] = list()
def plot(filename, column, label): data = py.loadtxt(filename).T X, Y = data[0], data[column] mask = (X >= xmin) * (X <= xmax) X, Y = X[mask], corrector(Y[mask]) aY, bY = np.min(Y), np.max(Y) pad = 7 if aY < 0 and -bY/aY < 10 else 0 py.ylabel(r'$' + label + r'$', y=y_coord, labelpad=8-pad, rotation=0) py.plot(X, Y, '-', lw=1) py.xlabel(r'$\zeta$', labelpad=-5) py.xlim(xmin, xmax) ax = py.axes() ax.axhline(lw=.5, c='k', ls=':') specify_tics(np.min(Y), np.max(Y)) if inside: print "Plot inside plot" ax = py.axes([.25, .45, .4, .4]) mask = X <= float(sys.argv[7]) py.plot(X[mask], Y[mask], '-', lw=1) ax.tick_params(axis='both', which='major', labelsize=8) ax.axhline(lw=.5, c='k', ls=':') ax.xaxis.set_major_locator(MultipleLocator(0.5)) ax.yaxis.set_major_locator(LinearLocator(3)) ymin, _, ymax = ax.get_yticks() if (ymax + ymin) < (ymax-ymin)/5: y = max(ymax, -ymin) py.ylim(-y, y)
def plotSurface(pt, td, winds, map, stride, title, file_name): pylab.figure() pylab.axes((0.05, 0.025, 0.9, 0.9)) u, v = winds nx, ny = pt.shape gs_x, gs_y = goshen_3km_gs xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny)) data_thin = tuple([ slice(None, None, stride) ] * 2) td_cmap = matplotlib.cm.get_cmap('Greens') td_cmap.set_under('#ffffff') pylab.contourf(xs, ys, td, levels=np.arange(40, 80, 5), cmap=td_cmap) pylab.colorbar() CS = pylab.contour(xs, ys, pt, colors='r', linestyles='-', linewidths=1.5, levels=np.arange(288, 324, 4)) pylab.clabel(CS, inline_spacing=0, fmt="%d K", fontsize='x-small') pylab.quiver(xs[data_thin], ys[data_thin], u[data_thin], v[data_thin]) drawPolitical(map, scale_len=75) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
def plotwithstats(t, s): from matplotlib.ticker import NullFormatter nullfmt = NullFormatter() figure() ax2 = axes([0.125 + 0.5, 0.1, 0.2, 0.8]) ax1 = axes([0.125, 0.1, 0.5, 0.8]) ax1.plot(t, s) ax1.set_xticks(ax1.get_xticks()[:-1]) meanv = s.mean() mi = s.min() mx = s.max() sd = s.std() ax2.bar(-0.5, mx - mi, 1, mi, lw=2, color='#f0f0f0') ax2.bar(-0.5, sd * 2, 1, meanv - sd, lw=2, color='#c0c0c0') ax2.bar(-0.5, 0.2, 1, meanv - 0.1, lw=2, color='#b0b0b0') ax2.axis([-1, 1, ax1.axis()[2], ax1.axis()[3]]) ax2.yaxis.set_major_formatter(nullfmt) ax2.set_xticks([]) return ax1, ax2
def ConfigCAngles(): pylab.figure(figsize=(3.5, 3.5)) pylab.axes((0.0, 0.0, 1.0, 1.0)) geo = ps.LoadGeo() phi_i0 = geo.phi_i0 phi_is = geo.phi_is phi_ie = geo.phi_ie phi_o0 = geo.phi_o0 phi_os = geo.phi_os phi_oe = geo.phi_oe phi1 = np.linspace(phi_is, phi_ie, 1000) phi2 = np.linspace(phi_i0, phi_is, 1000) phi3 = np.linspace(phi_os, phi_oe, 1000) phi4 = np.linspace(phi_o0, phi_os, 1000) (xi1, yi1) = ps.coords_inv(phi1, geo, 0, "fi") (xi2, yi2) = ps.coords_inv(phi2, geo, 0, "fi") (xo1, yo1) = ps.coords_inv(phi3, geo, 0, "fo") (xo2, yo2) = ps.coords_inv(phi4, geo, 0, "fo") #### Inner and outer involutes pylab.plot(xi1, yi1, "k", lw=1) pylab.plot(xi2, yi2, "k:", lw=1) pylab.plot(xo1, yo1, "k", lw=1) pylab.plot(xo2, yo2, "k:", lw=1) ### Innver involute labels pylab.plot(xi2[0], yi2[0], "k.", markersize=5, mew=2) pylab.text(xi2[0], yi2[0] + 0.0025, "$\phi_{i0}$", size=8, ha="right", va="bottom") pylab.plot(xi1[0], yi1[0], "k.", markersize=5, mew=2) pylab.text(xi1[0] + 0.002, yi1[0], "$\phi_{is}$", size=8) pylab.plot(xi1[-1], yi1[-1], "k.", markersize=5, mew=2) pylab.text(xi1[-1] - 0.002, yi1[-1], " $\phi_{ie}$", size=8, ha="right", va="center") ### Outer involute labels pylab.plot(xo2[0], yo2[0], "k.", markersize=5, mew=2) pylab.text(xo2[0] + 0.002, yo2[0], "$\phi_{o0}$", size=8, ha="left", va="top") pylab.plot(xo1[0], yo1[0], "k.", markersize=5, mew=2) pylab.text(xo1[0] + 0.002, yo1[0], "$\phi_{os}$", size=8) pylab.plot(xo1[-1], yo1[-1], "k.", markersize=5, mew=2) pylab.text(xo1[-1] - 0.002, yo1[-1], " $\phi_{oe}$", size=8, ha="right", va="center") ### Base circle t = np.linspace(0, 2 * pi, 100) pylab.plot(geo.rb * np.cos(t), geo.rb * np.sin(t), "b-") pylab.plot(np.r_[0, geo.rb * np.cos(9 * pi / 8)], np.r_[0, geo.rb * np.sin(9 * pi / 8)], "k-") pylab.text( geo.rb * np.cos(9 * pi / 8) + 0.0005, geo.rb * np.sin(9 * pi / 8) + 0.001, "$r_b$", size=8, ha="right", va="top" ) pylab.axis("equal") pylab.setp(pylab.gca(), "ylim", (min(yo1) - 0.005, max(yo1) + 0.005)) pylab.axis("off") pylab.savefig("FixedScrollAngles.png", dpi=600) pylab.savefig("FixedScrollAngles.eps") pylab.savefig("FixedScrollAngles.pdf") pylab.close()
def __init__(self, cut_coords, axes=None, black_bg=False): """ Create 3 linked axes for plotting orthogonal cuts. Parameters ---------- cut_coords: 3 tuple of ints The cut position, in world space. axes: matplotlib axes object, optional The axes that will be subdivided in 3. black_bg: boolean, optional If True, the background of the figure will be put to black. If you whish to save figures with a black background, you will need to pass "facecolor='k', edgecolor='k'" to pylab's savefig. """ self._cut_coords = cut_coords if axes is None: axes = pl.axes((0., 0., 1., 1.)) axes.axis('off') self.frame_axes = axes axes.set_zorder(1) bb = axes.get_position() self.rect = (bb.x0, bb.y0, bb.x1, bb.y1) self._object_bounds = dict() self._black_bg = black_bg # Create our axes: self.axes = dict() for index, name in enumerate(('x', 'y', 'z')): ax = pl.axes([0.3*index, 0, .3, 1]) ax.axis('off') self.axes[name] = ax ax.set_axes_locator(self._locator) self._object_bounds[ax] = list()
def initPylab(postscript): pylab.hold = True if postscript: inches_per_pt = 1.0/72.27 golden_mean = (5.0**0.5+1)/2.0 figwidth=246. * inches_per_pt figheight = (figwidth / golden_mean) left = 0.2 bottom = 0.25 right = 0.95 top = 0.90 params = {'font.size':10, 'axes.labelsize':10, 'axes.titlesize':10, 'text.fontsize':10, 'xtick.labelsize':10, 'ytick.labelsize':10, 'text.usetex':True, 'backend':'ps', 'figure.figsize': [figwidth/(right-left),figheight/(top-bottom)] } pylab.rcParams.update(params) pylab.figure(1) pylab.clf() pylab.axes([left,bottom,right-left,top-bottom])
def set_font(font): pl.xlabel('String length', fontproperties=font) pl.tight_layout() for label in pl.axes().get_xticklabels(): label.set_fontproperties(font) for label in pl.axes().get_yticklabels(): label.set_fontproperties(font)
def evaluate( self, *args, **params): data = args[0] rowLabels= args[1] colLabels= self.selectedColNames plt= pltobj( None, xlabel= "", ylabel= self.rowlabelsCol, title= __(self.name) ) plt.hold(True) rows = len(data) colours= ['b']*rows ind = arange( len( colLabels)) + 0.3 # the x locations for the groups cellText = [] width = 0.5 # the width of the bars yoff = array([ 0.0] * len( colLabels)) # the bottom values for stacked bar chart for row in xrange( rows): plt.bar( ind, data[row], width, bottom=yoff, color= colours[row]) yoff = yoff + data[row] cellText.append( ['%1.1f' % (x/1000.0) for x in yoff]) # Add a table at the bottom of the axes axes( [0.2, 0.2, 0.7, 0.6]) colours.reverse() cellText.reverse() the_table = plt.gca().table( cellText = cellText, rowLabels = rowLabels, rowColours = colours, colLabels = colLabels, loc = 'bottom') plt.set_xticks([]) plt.hold( False) plt.updateControls() plt.canvas.draw() axes([0.2, 0.2, 0.7, 0.7]) return plt
def plot_eigenmodes(evecs, evals, ax_list, mode_list, RArange, DECrange): """ Plot KL eigenmodes associated with the COSMOS catalog """ assert len(ax_list) == len(mode_list) NRA = len(RArange) - 1 NDEC = len(DECrange) - 1 for i in range(len(ax_list)): ax = ax_list[i] mode = mode_list[i] pylab.axes(ax) evec = evecs[:, i] pylab.imshow( evec.reshape((NRA, NDEC)).T, origin="lower", interpolation=None, #'nearest', cmap=pylab.cm.RdGy, extent=(RArange[0], RArange[-1], DECrange[0], DECrange[-1]), ) cmax = np.max(abs(evec)) pylab.clim(-cmax, cmax) pylab.title(r"$\mathrm{mode\ %i}\ (v=%.3f)$" % (i + 1, evals[i])) return ax_list
def make_lexicon_pie(input_dict, title): e = 0 f = 0 n = 0 l = 0 g = 0 o = 0 for word in input_dict.keys(): label = input_dict[word] if label == "English": e += 1 elif label == "French": f += 1 elif label == "Norse": n += 1 elif label == "Latin": l += 1 elif label == "Greek": g += 1 else: o += 1 total = e + f + n + l + g + o fracs = [o/total, n/total, g/total, l/total, f/total, e/total] labels = 'Other', 'Norse', 'Greek', 'Latin', 'French', 'English' pl.figure(figsize=(6, 6)) pl.axes([0.1, 0.1, 0.8, 0.8]) pl.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) pl.title(title) pl.show()
def create_top_stacked_axes(self,heights=(1.)): """ Create several axes for subplot on top of each other Args: heights (iterable): relative height e.g. heights = [.2,.1,.6] will give axes using this amount of space """ assert sum(heights) <= 1., "heights must be in relative heights" cfg = get_config_item("canvas") left = cfg["leftpadding"] right = cfg["rightpadding"] bot = cfg["bottompadding"] top = cfg["toppadding"] width = 1. - left - right height = 1. - top - bot heights = [height*h for h in heights] heights.reverse() Logger.debug("Using heights {0}".format(heights.__repr__())) abs_bot = 0 +bot axes = [p.axes([left,abs_bot,width,heights[0]])] restheights = heights[1:] abs_bot = bot + heights[0] for h in restheights: theaxes = p.axes([left,abs_bot,width,h]) p.setp(theaxes.get_xticklabels(), visible=False) axes.append(theaxes) abs_bot += h self.axes = axes
def plot_pincrdr_probs( f = None ): hist, bins = np.histogram( p_inc_rdr, bins = yaml_config['rdr_histbins']['bins'], range = (yaml_config['rdr_histbins']['min'], yaml_config['rdr_histbins']['max']) ) bin_width = bins[1] - bins[0] # Find out which bin each read belongs to. # Sanity check: print [ sum( bins_ind == i ) for i in xrange(len(hist)) ] => equals hist bins_ind = np.sum( p_inc_rdr[:,np.newaxis] > bins[:-1], axis = 1 ) - 1 prob_read = [ sum(rssi[bins_ind == i] != -1)*1.0 / hist[i] # positive reads / total reads for bin i for i in xrange(len(hist)) # same as len(bins)-1 if hist[i] != 0 ] # only where we have data! (also prevents div by 0) if not f: f = pl.figure( figsize=(10,6) ) pl.axes([0.1,0.1,0.65,0.8]) pos_bars = pl.bar([ bins[i] for i in xrange(len(hist)) if hist[i] != 0 ], # Only plot the bars for places we have data! prob_read, # This is only defined for ones that have data! width = bin_width, color = 'b', alpha = 0.7 ) pl.hold( True ) neg_bars = pl.bar([ bins[i] for i in xrange(len(hist)) if hist[i] != 0 ], # Only plot the bars for places we have data! [ 1.0 - p for p in prob_read ], # This is only defined for ones that have data! width = bin_width, bottom = prob_read, color = 'r', alpha = 0.7 ) pl.axis([ yaml_config['rdr_axis'][0], yaml_config['rdr_axis'][1], 0.0, 1.0 ]) pl.xlabel( '$P^{inc}_{rdr}$ (dBm)') pl.ylabel( 'Probability of Tag Read / No-Read') pl.title( 'Probability of Tag Read / No-Read vs Predicted Power at Reader ' ) pl.legend((pos_bars[0], neg_bars[0]), ('P( read )', 'P( no read )'), loc=(1.03,0.2)) return f
def plot_all(): pylab.axes() x = [x0, x1, x2, x3, x4, x5, x6, x7, x8] y = [y0, y1, y2, y3, y4, y5, y6, y7, y8] plt.title('Retroreflective Sphere') plt.plot(x, y) plt.xlim(-0.1, 0.1) plt.ylim(-0.13, 0.1) plt.xlabel(u"[m]") plt.ylabel(u"[m]") point_num = 0 for i, j in izip(x, y): if withCoords: plt.annotate("M%s\n" % point_num + "[%2.3e," % i + "%2.3e]" % j, xy=(i, j)) point_num += 1 if withArrows: for i in xrange(len(x) - 1): plt.arrow(x[i], y[i], x[i + 1] - x[i], y[i + 1] - y[i], head_width=0.005, head_length=0.004, fc="k", ec="k", width=0.00003)
def plot_mesh(pts, tri, *args): if len(args) > 0: tripcolor(pts[:,0], pts[:,1], tri, args[0], edgecolor='black', cmap="Blues") else: triplot(pts[:,0], pts[:,1], tri, "k-", lw=2) axis('tight') axes().set_aspect('equal')
def plot_nodes(pts, mask, *args): boundary = pts[mask == True] interior = pts[mask == False] plot(boundary[:,0], boundary[:,1], 'o', color="red") plot(interior[:,0], interior[:,1], 'o', color="white") axis('tight') axes().set_aspect('equal')
def plot_matplot_lib(df, show=False): header = list(df.columns.values) fig = plt.figure(figsize=(df.shape[1] * 2 + 2, 12)) xs, ys = generateDotPlot(np.asarray(df), space=0.15, width=5) x = [[i*2, h] for i, h in enumerate(header)] plt.scatter(x=xs, y=ys, facecolors='black',marker='o', s=15) plt.axes().set_aspect('equal') plt.axes().set_autoscale_on(False) plt.axes().set_ybound(0,6) plt.axes().set_xbound(-0.9, len(header) * 2 + 0.9) plt.xticks(zip(*x)[0], zip(*x)[1] ) plt.yticks(range(1,6)) for tick in plt.axes().get_xaxis().get_major_ticks(): tick.set_pad(15) tick.label1 = tick._get_text1() for tick in plt.axes().get_yaxis().get_major_ticks(): tick.set_pad(15) tick.label1 = tick._get_text1() plt.setp(plt.xticks()[1], rotation=20) if show: plt.show() return fig
def plot_mesh(pts, tri, *args): if len(args) > 0: tripcolor(pts[:, 0], pts[:, 1], tri, args[0], edgecolor="black", cmap="Blues") else: triplot(pts[:, 0], pts[:, 1], tri, "k-", lw=2) axis("tight") axes().set_aspect("equal")
def animate(self,e,draw_bottoms=True, draw_circles=False, draw_circle_events=True): global i global past_circle_events filename = 'tmp-{0:03}.png'.format(i) #print 'animate', e, type(e), isinstance(e,voronoi.SiteEvent), isinstance(e,voronoi.CircleEvent) plt.clf() fig = plt.gcf() # plt.axis([0,width, 0, height]) if self.bounding_box is not None: plt.axis(self.bounding_box) #plt.axis([-5,25, -5, 25]) _draw_beachline(e, self.T) _draw_hedges(e, self.edges) if draw_circle_events: _draw_circle_events(e, self.Q, past_circle_events, draw_bottoms, draw_circles, fig) plot_directrix(e.y) plot_points(self.input) if e.is_site: plot_points([e.site], color='black') plt.grid(True) axes().set_aspect('equal', 'datalim') fig.savefig(filename, bbox_inches='tight') print filename, 'beachline', self.T, 'Input:', self.input i+=1
def add_colorbar(handle,**args): ax=pl.gca() Data,err = opt.get_plconf(plconf,'AXES') cbpos = Data['cbpos'][ifig] cbbgpos = Data['cbbgpos'][ifig] cbbgc = Data['cbbgcolor'][ifig] cbbga = Data['cbbgalpha'][ifig] cblab = Data['cblabel'][ifig] # colorbar bg axes: if cbbgpos: rec=pl.axes((cbpos[0]-cbpos[2]*cbbgpos[0],cbpos[1]-cbbgpos[2]*cbpos[3], cbpos[2]*(1+cbbgpos[0]+cbbgpos[1]),cbpos[3]*(1+cbbgpos[2]+cbbgpos[3])), axisbg=cbbgc,frameon=1) rec.patch.set_alpha(cbbga) rec.set_xticks([]) rec.set_yticks([]) for k in rec.axes.spines.keys(): rec.axes.spines[k].set_color(cbbgc) rec.axes.spines[k].set_alpha(cbbga) # colorbar: if cbpos: cbax=fig.add_axes(cbpos) if cbpos[2]>cbpos[3]: orient='horizontal' else: orient='vertical' cb=pl.colorbar(handle,cax=cbax,orientation=orient,drawedges=0,**args) pl.axes(ax) # colorbar label: cb.set_label(r'Wind Speed [m s$^{\rm{-1}}$]')
def plotTiming(vortex_prob, vortex_times, times, map, grid_spacing, tornado_track, title, file_name, obs=None, centers=None, min_prob=0.1): nx, ny = vortex_prob.shape gs_x, gs_y = grid_spacing xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny)) time_color_map = matplotlib.cm.Accent time_color_map.set_under('#ffffff') vortex_times = np.where(vortex_prob >= min_prob, vortex_times, -1) track_xs, track_ys = map(*reversed(tornado_track)) pylab.figure(figsize=(10, 8)) pylab.axes((0.025, 0.025, 0.95, 0.925)) pylab.pcolormesh(xs, ys, vortex_times, cmap=time_color_map, vmin=times.min(), vmax=times.max()) tick_labels = [ (datetime(2009, 6, 5, 18, 0, 0) + timedelta(seconds=int(t))).strftime("%H%M") for t in times ] bar = pylab.colorbar()#orientation='horizontal', aspect=40) bar.locator = FixedLocator(times) bar.formatter = FixedFormatter(tick_labels) bar.update_ticks() pylab.plot(track_xs, track_ys, 'mv-', lw=2.5, mfc='k', ms=8) drawPolitical(map, scale_len=(xs[-1, -1] - xs[0, 0]) / 10.) pylab.title(title) pylab.savefig(file_name) pylab.close()
for i, trace in enumerate(l): x = numpy.linspace(-numpy.pi * 3, numpy.pi * 3, len(trace)) norm = sum(trace) * (x[-1] - x[0]) / len(x) ax.plot(x, trace / norm, color=colors[i]) ax.set_xlim([-numpy.pi, numpy.pi]) sm = pylab.cm.ScalarMappable(cmap='copper', norm=pylab.normalize(vmin=2.5, vmax=20)) sm._A = [] box = ax.get_position() pos = [ box.x0 + 1.03 * box.width, box.y0 + box.height * 0.1, 0.01, box.height * 0.8 ] axColor = pylab.axes(pos) cbar = pylab.colorbar(sm, cax=axColor) tick_locator = ticker.MaxNLocator(nbins=4) cbar.locator = tick_locator cbar.update_ticks() cbar.ax.tick_params(length=1, ) ax.text(1.25, 0.5, r'Delay CTX$\to$STN (ms)', transform=ax.transAxes, va='center', rotation=270) ax.set_xlabel(r'Angle (rad)') ax.set_ylabel('Norm. count ST-TI') ax.my_set_no_ticks(xticks=4)
right_tick = (i+1)%numCols==0 for tick in ax.yaxis.get_major_ticks(): tick.label1On=left_tick tick.label2On=right_tick lower_tick = i>=(numRows-1)*numCols for tick in ax.xaxis.get_major_ticks(): tick.label1On=lower_tick subplots.append(ax) return subplots if __name__=='__main__': subplots = panelplot(3,3) from numpy import arange x = arange(20) for ax in subplots: # set this to be the current axes pl.axes(ax) pl.plot(x,x) pl.ylim(0,19.9) pl.xlim(0,19.9) pl.show()
def multi_plot(plist, plottype='whisker', Nequil=Nequil_default, funcname='occupancy_mean_correl', **kwargs): """Display a collection of functions. multi_plot(plist,plottype='whisker',Nequil=10000,funcname='occupancy_mean_correl',**kwargs) The function is obtained from a method call on the objects in plist. The assumption is that these are functions of Ntotal (if not, set Nequil=0; Nequil is added to x). Each object is a different realization, e.g. multiple MCMC runs. plottype 'whisker' (whisker plot), 'standard' (average and standard deviations) Nequil correction, added to x funcname string; a method of the objects in plist that does EXACTLY the following: x,y = obj.funcname() where x and y are numpy arrays of equal length **kwargs color, boxcolor, mediancolor, capsize """ import pylab plottypes = ('whisker', 'standard') # sanity checks if plottype not in plottypes: raise ValueError( "Only plottypes from %(plottypes)r, not %(plottype)s." % locals()) try: plist[0].__getattribute__(funcname)( ) # How do I handle old-style classes? Check __getattr__? except: raise ValueError( "funcname='%(funcname)r' has the wrong signature or is not a method " "of the objects in plist." % locals()) def xy_from(obj): return obj.__getattribute__(funcname)() def x_from(obj): return xy_from(obj)[0] def y_from(obj): return xy_from(obj)[1] kwargs.setdefault('color', 'b') # main color kwargs.setdefault('capsize', 0) x = x_from(plist[0]) + Nequil all_y = numpy.array([y_from(p) for p in plist]) ymean = all_y.mean(axis=0) yerr = all_y.std(axis=0) ax = pylab.axes(frameon=False) if plottype == 'standard': lines = pylab.errorbar(x, ymean, yerr=yerr, fmt='o', linestyle='-', **kwargs) for p in plist: px, py = xy_from(p) px += Nequil components = pylab.semilogx(px, py, 'o', color=kwargs['color'], ms=3) elif plottype == 'whisker': # widths that look the same in a log plot def logwidth(x, delta): """Return linear widths at x that, logarithmically scaled, appear to be delta wide.""" q = numpy.exp(delta) return x * (1 - q) / (1 + q) kwargs.setdefault('mediancolor', 'k') # for median in whiskerplot kwargs.setdefault('boxcolor', 'darkgray') pylab.semilogx(x, ymean, 'o-', color=kwargs['color'], ms=3) components = pylab.boxplot(all_y, positions=x, widths=logwidth( x, kwargs.setdefault('widths', 0.15))) ax = pylab.gca() ax.set_xscale('log') ax.set_yscale('linear') # must modify components for customisation for l in components['boxes']: l.set_color(kwargs['boxcolor']) for l in components['whiskers']: l.set_color(kwargs['color']) l.set_linestyle('-') for l in components['caps']: l.set_color(kwargs['color']) for l in components['medians']: l.set_color(kwargs['mediancolor']) l.set_linewidth(3.0) for l in components['fliers']: l.set_color(kwargs['color']) pylab.draw_if_interactive() pylab.xlabel('total MCMC steps') pylab.ylabel('correlation coefficient with MD') pylab.title('convergence of occupancy correlation with MD')
inf_low.append(msims[scen].results['new_infections'].low[wd]) inf_high.append(msims[scen].results['new_infections'].high[wd]) epsx = 0.003 llpad = 0.01 lockdown1 = [sim.day('2020-03-23'),sim.day('2020-05-31')] lockdown2 = [sim.day('2020-11-05'),sim.day('2020-12-03')] lockdown3 = [sim.day('2021-01-05'),sim.day('2021-03-08')] for nc in range(ncols): pl.figtext(xgapl + (dx + xgapm) * nc + epsx, ygapb + dy * nrows + ygapm * (nrows - 1) + llpad, labels[nc], fontsize=36, fontweight='bold', bbox={'edgecolor': 'none', 'facecolor': 'white', 'alpha': 0.5, 'pad': 4}) for pn in range(nplots): ax[pn] = pl.axes([xgapl + (dx + xgapm) * (pn % ncols), ygapb + (ygapm + dy) * (pn // ncols), dx, dy]) print([xgapl + (dx + xgapm) * (pn % ncols), ygapb + (ygapm + dy) * (pn // ncols)]) print(list(sims.keys())[pn % ncols]) format_ax(ax[pn], sim) if (pn%ncols) != 0: ax[pn].set_yticklabels([]) else: ax[pn].set_ylabel('New infections') if pn in range(ncols): plotter('r_eff', sims[pn % ncols], ax[pn]) ax[pn].set_ylim(0, 3.5) ax[pn].axhline(y=1, color='red', linestyle='--') if (pn%ncols) == 0: ax[pn].set_ylabel('R')
def main(): parse_again = False # True # directories of sampled pdbs and pdbtms pdb_dir = "train_pdb_structures/" pdbtm_dir = "pdbtm_structures/" # defining all one letter code amino acids global aas aas = list(string.ascii_uppercase) for no_aa in ["B", "J", "O", "U", "X", "Z"]: aas.remove(no_aa) # Get all pdbtm ids + chain f = open('data/pdbtm_all_list.txt', 'r') pdbtm_all_ids = f.readlines() f.close() if parse_again: pdbs = os.listdir(pdb_dir) pdbtms = os.listdir(pdbtm_dir) pdb_aa_helices, pdbtm_aa_helices, pdb_aa_helices_rel, pdbtm_aa_helices_rel = parse_files( pdbs, pdbtms, pdbtm_all_ids, pdb_dir, pdbtm_dir) export_(pdb_aa_helices, pdbtm_aa_helices, pdb_aa_helices_rel, pdbtm_aa_helices_rel) else: pdb_aa_helices, pdbtm_aa_helices, pdb_aa_helices_rel, pdbtm_aa_helices_rel = import_( ) # Boxplots of amino acid distributions print("Plotting Boxplots...") # Relative values without outliers # all together fig = figure(figsize=(12, 6)) ax = axes() nr_aas = len(aas) bp = boxplot(get_distribution(pdbtm_aa_helices_rel, aas), positions=[6 + x * 3 - 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "blue") bp = boxplot(get_distribution(pdb_aa_helices_rel, aas), positions=[4 + x * 3 + 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "black") ylim(0, 0.3) ax.set_xticklabels([""] + aas + [""]) ax.set_xticks([2 + x * 3 for x in range(nr_aas + 2)]) # draw temporary red and blue lines and use them to create a legend hB, = plot([1, 1], 'k-', color='black') hR, = plot([1, 1], 'k-', color='blue') legend((hB, hR), ('NON-TM helices', 'TM helices')) hB.set_visible(False) hR.set_visible(False) savefig('figures/boxplot_rel_all_aas_without_outliers.png') # hydrophobic aas fig = figure(figsize=(8, 6)) ax = axes() #plt.figure(figsize=(12, 6)) hydrophobic = ["C", "F", "G", "I", "L", "V", "W"] nr_aas = len(hydrophobic) bp = boxplot(get_distribution(pdbtm_aa_helices_rel, hydrophobic), positions=[6 + x * 3 - 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "blue") bp = boxplot(get_distribution(pdb_aa_helices_rel, hydrophobic), positions=[4 + x * 3 + 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "black") ylim(0, 0.3) ax.set_xticklabels([""] + hydrophobic + [""]) ax.set_xticks([2 + x * 3 for x in range(nr_aas + 2)]) # draw temporary red and blue lines and use them to create a legend hB, = plot([1, 1], 'k-', color='black') hR, = plot([1, 1], 'k-', color='blue') legend((hB, hR), ('NON-TM helices', 'TM helices')) hB.set_visible(False) hR.set_visible(False) savefig('figures/boxplot_rel_hydrophobic_without_outliers.png') # Plotting hydrophlic amino acids fig = figure(figsize=(8, 6)) ax = axes() hydrophilic = ["D", "E", "K", "R"] nr_aas = len(hydrophilic) bp = boxplot(get_distribution(pdbtm_aa_helices_rel, hydrophilic), positions=[6 + x * 3 - 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "blue") bp = boxplot(get_distribution(pdb_aa_helices_rel, hydrophilic), positions=[4 + x * 3 + 0.6 for x in range(nr_aas)], widths=0.6, showfliers=False) setBoxColors(bp, "black") ylim(0, 0.3) ax.set_xticklabels([""] + hydrophilic + [""]) ax.set_xticks([2 + x * 3 for x in range(nr_aas + 2)]) # draw temporary red and blue lines and use them to create a legend hB, = plot([1, 1], 'k-', color='black') hR, = plot([1, 1], 'k-', color='blue') legend((hB, hR), ('NON-TM helices', 'TM helices')) hB.set_visible(False) hR.set_visible(False) savefig('figures/boxplot_rel_hydrophilic_without_outliers.png')
# the nodes (the stocks) on a 2D plane # We use a dense eigen_solver to achieve reproducibility (arpack is # initiated with random vectors that we don't control). In addition, we # use a large number of neighbors to capture the large-scale structure. node_position_model = manifold.LocallyLinearEmbedding(n_components=2, eigen_solver='dense', n_neighbors=6) embedding = node_position_model.fit_transform(X.T).T ############################################################################### # Visualization pl.figure(1, facecolor='w', figsize=(10, 8)) pl.clf() ax = pl.axes([0., 0., 1., 1.]) pl.axis('off') # Display a graph of the partial correlations partial_correlations = edge_model.precision_.copy() d = 1 / np.sqrt(np.diag(partial_correlations)) partial_correlations *= d partial_correlations *= d[:, np.newaxis] non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02) # Plot the nodes using the coordinates of our embedding pl.scatter(embedding[0], embedding[1], s=100 * d**2, c=labels, cmap=pl.cm.spectral)
def plot_spectra(date_central="2017-02-08 02:40:00", tw=3, e_factor=0.01, xmin=-6, xmax=12, ymin=0, ymax=3.2, mMZe=[-20, 20], mMW=[-2, 2], path='Data/DDU/MK_processed/', TRES=60): #tw = temporal window #date_central = "%Y-%m-%d %H:%M:%S" from netCDF4 import Dataset from calendar import timegm import pylab, time import numpy as np #Font format font = {'family': 'serif', 'weight': 'normal', 'size': 15} pylab.rc('font', **font) ##Date time utc_time = time.strptime(date_central, "%Y-%m-%d %H:%M:%S") epoch_time = timegm(utc_time) dday = time.strftime("%Y%m%d", time.gmtime(epoch_time)) filename = path + dday[:6] + '/' + 'DDU_' + dday + '_' + str( int(TRES)) + 'TRES.nc' #Open dataset dataset = Dataset(filename) #reading variables ##W = dataset.variables["W"][:] ##spectralWidth = dataset.variables["spectralWidth"][:] ##SNR = dataset.variables["SNR"][:] ##quality = dataset.variables["quality"][:] H = dataset.variables["height"][:] Time = dataset.variables["time"][:] #t = Time[1000] pixint = np.where(min(abs(Time - epoch_time)) == abs(Time - epoch_time))[0][0] eta = dataset.variables["eta"][pixint - tw + 1:pixint + 1, :, :] etaMask = dataset.variables["etaMask"][pixint - tw + 1:pixint + 1, :, :] Ze2 = np.nanmean(dataset.variables["Ze"][pixint - tw + 1:pixint + 1, :], axis=0) eta = np.nanmean(eta, axis=0) etaMask = np.nanmean(etaMask, axis=0) # conversion into dZe/dv lamb = 299792458. / 24.15e9 #wavelenght K2 = 0.92 eta = 10**18 * (lamb**4 * eta / (np.pi**5 * 0.92)) dv = 0.1893669 vf = dv * (np.linspace(0, 191, 192) - 64) #masking noise etaM = np.ma.masked_where(etaMask == 1, eta) etaM2 = np.ma.masked_where((1 - etaMask) == 1, eta) f, axarr = pylab.subplots(1, 2, sharey='row', figsize=(12, 8)) Ze = [] Ze.append(-9999) Ze.append(-9999) Ze.append(-9999) #Plotting pylab.axes(axarr[0]) for ih in range(3, 31): pylab.plot(vf, (etaM[ih, :] - np.nanmin(etaM2[ih, 64:128])) * e_factor + 0.1 * ih, color="black") pylab.plot(vf, (eta[ih, :] - np.nanmin(etaM2[ih, 64:128])) * e_factor + 0.1 * ih, ":", color="black") #print np.nanmin(etaM[ih,:]-np.nanmean(etaM2[ih,:])),np.nanmax(etaM[ih,:]-np.nanmean(etaM2[ih,:])) if (np.nansum(etaM[ih, :]) != np.nan): Ze.append(10 * np.log10(np.nansum(etaM[ih, :]))) else: Ze.append(-9999) Ze = np.array(Ze) Ze = np.ma.masked_where(Ze == -9999, Ze) W = np.zeros(shape=np.shape(Ze)) nv = 0 for v in vf: W = W + etaM[:, nv].filled(0) * v nv = nv + 1 W = W / 10.**(Ze / 10.) pylab.axis([xmin, xmax, ymin, ymax]) pylab.xlabel("Doppler velocity [m s" + r'$^{-1}$' + "]") pylab.ylabel("Height [m]") pylab.title("MK12 spectra " + date_central) pylab.axes(axarr[1]) p1, = pylab.plot(W, H[0] / 1000., color='red', label="W") pylab.xlabel("W [m s" + r'$^{-1}$' + "]") pylab.axis([mMW[0], mMW[1], ymin, ymax]) ax = axarr[1].twiny() p2, = ax.plot(Ze, H[0] / 1000., color='blue', label="Ze") ax.set_xlabel("Ze [dBZe]") pylab.axis([mMZe[0], mMZe[1], ymin, ymax]) pylab.legend(handles=[p1, p2], frameon=False) #pylab.savefig(path_out,format="png",bbox_inches = 'tight', dpi=600) pylab.show()
def create_main_frame(self): self.main_frame = QWidget() #self.main_frame.resize(800, 400) self.main_frame.setFixedSize(820, 700) self.dpi = 80 self.fig = pl.figure(num=None, figsize=(10, 5), dpi=self.dpi, facecolor='w', edgecolor='k') self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.axesa = pl.axes([0.07, 0.1, 0.4, 0.88]) self.axesb = pl.axes([0.57, 0.1, 0.4, 0.88]) # Bind the 'pick' event for clicking on one of the bars # self.canvas.mpl_connect('pick_event', self.on_pick) # Create the navigation toolbar, tied to the canvas # self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Other GUI controls # # self.sbox_label_h0 = QLabel(u'\u0048'u'\u0030') self.sbox_label_h0 = QLabel("H<sub>0</sub>") self.sbox_label_h0.setFixedWidth(20) self.sbox_h0 = QDoubleSpinBox() self.sbox_h0.setSingleStep(100 / nsbox) self.sbox_h0.setFocusPolicy(Qt.StrongFocus) self.sbox_h0.setFixedWidth(sbox_len) self.sbox_h0.setRange(0, 100.0) self.sbox_h0.setValue(67.81) self.sbox_label_om = QLabel(u'\u03a9' "<sub>m</sub>") self.sbox_label_om.setFixedWidth(20) self.sbox_om = QDoubleSpinBox() self.sbox_om.setSingleStep(1.0 / nsbox) self.sbox_om.setFocusPolicy(Qt.StrongFocus) self.sbox_om.setFixedWidth(sbox_len) self.sbox_om.setRange(0, 1.0) self.sbox_om.setValue(0.308) self.sbox_label_ol = QLabel(u'\u03a9' "<sub>" u'\u039b' "</sub>") self.sbox_label_ol.setFixedWidth(20) self.sbox_ol = QDoubleSpinBox() self.sbox_ol.setSingleStep(1.0 / nsbox) self.sbox_ol.setFocusPolicy(Qt.StrongFocus) self.sbox_ol.setFixedWidth(sbox_len) self.sbox_ol.setRange(0, 1.0) self.sbox_ol.setValue(0.692) self.cb_cosmo = QComboBox() self.cb_cosmo.addItems(["Planck15", "WMP9", "Concordance"]) self.cb_cosmo.currentTextChanged.connect(self.update_sbox_pars) self.cb_models = QComboBox() self.cb_models.addItems(["SIE", "NFW", "PIEMD"]) #self.cb_models.currentIndexChanged.connect(self.selectionchange) self.cb_codes = QComboBox() self.cb_codes.addItems( ["Scipy", "Q-Lens", "Lensed", "LensTool", "Gravlens", "Glafic"]) #self.cb.currentIndexChanged.connect(self.selectionchange) self.draw_button = QPushButton("&Optimize") #self.draw_button.clicked.connect(lambda: self.optmization_actions("lensed")) self.draw_button.clicked.connect(self.optimization_actions) #self.grid_cb = QCheckBox("Show &Grid") #self.grid_cb.setChecked(False) #self.grid_cb.stateChanged.connect(self.on_draw) #int #------- self.slider_label_re = QLabel("R<sub>e</sub>") self.slider_re = QSlider(Qt.Horizontal) self.slider_re.setFocusPolicy(Qt.StrongFocus) self.slider_re.setFixedWidth(slider_len) self.slider_re.setRange(0, nbins) self.slider_re.setValue(st_re) self.slider_re.setTracking(True) self.slider_re.valueChanged.connect(self.on_draw) #int self.sbox_re = QDoubleSpinBox() self.sbox_re.setSingleStep(re_max / nsbox) self.sbox_re.setFocusPolicy(Qt.StrongFocus) self.sbox_re.setFixedWidth(sbox_len) self.sbox_re.setRange(0, re_max) self.sbox_re.setValue(re_max * st_re * 1.0 / nbins) self.slider_re.valueChanged.connect(self.update_sbox_re) self.sbox_re.editingFinished.connect(self.update_slider_re) #------- self.slider_label_x1 = QLabel("x<sub>1</sub>") self.slider_x1 = QSlider(Qt.Horizontal) self.slider_x1.setFocusPolicy(Qt.StrongFocus) self.slider_x1.setFixedWidth(slider_len) self.slider_x1.setRange(0, nbins) self.slider_x1.setValue(st_x1) self.slider_x1.setTracking(True) self.slider_x1.valueChanged.connect(self.on_draw) #int self.sbox_x1 = QDoubleSpinBox() self.sbox_x1.setSingleStep((x1_max - x1_min) / nsbox) self.sbox_x1.setFocusPolicy(Qt.StrongFocus) self.sbox_x1.setFixedWidth(sbox_len) self.sbox_x1.setRange(x1_min, x1_max) self.sbox_x1.setValue(st_x1 * dpl + x1_min) self.slider_x1.valueChanged.connect(self.update_sbox_x1) self.sbox_x1.editingFinished.connect(self.update_slider_x1) #------- self.slider_label_x2 = QLabel("x<sub>2</sub>") self.slider_x2 = QSlider(Qt.Horizontal) self.slider_x2.setFocusPolicy(Qt.StrongFocus) self.slider_x2.setFixedWidth(slider_len) self.slider_x2.setRange(0, nbins) self.slider_x2.setValue(st_x2) self.slider_x2.setTracking(True) self.slider_x2.valueChanged.connect(self.on_draw) #int self.sbox_x2 = QDoubleSpinBox() self.sbox_x2.setSingleStep((x2_max - x2_min) / nsbox) self.sbox_x2.setFocusPolicy(Qt.StrongFocus) self.sbox_x2.setFixedWidth(sbox_len) self.sbox_x2.setRange(x2_min, x2_max) self.sbox_x2.setValue(st_x2 * dpl + x2_min) self.slider_x2.valueChanged.connect(self.update_sbox_x2) self.sbox_x2.editingFinished.connect(self.update_slider_x2) #------- self.slider_label_ql = QLabel("q<sub>lens</sub>") self.slider_ql = QSlider(Qt.Horizontal) self.slider_ql.setFocusPolicy(Qt.StrongFocus) self.slider_ql.setFixedWidth(slider_len) self.slider_ql.setRange(0, nbins) self.slider_ql.setValue(st_ql) self.slider_ql.setTracking(True) self.slider_ql.valueChanged.connect(self.on_draw) #int self.sbox_ql = QDoubleSpinBox() self.sbox_ql.setSingleStep(ql_max / nsbox) self.sbox_ql.setFocusPolicy(Qt.StrongFocus) self.sbox_ql.setFixedWidth(sbox_len) self.sbox_ql.setRange(0, ql_max) self.sbox_ql.setValue(ql_max * st_ql * 1.0 / nbins) self.slider_ql.valueChanged.connect(self.update_sbox_ql) self.sbox_ql.editingFinished.connect(self.update_slider_ql) #------- self.slider_label_la = QLabel(u'\u03b8' "<sub>lens</sub>") self.slider_la = QSlider(Qt.Horizontal) self.slider_la.setFocusPolicy(Qt.StrongFocus) self.slider_la.setFixedWidth(slider_len) self.slider_la.setRange(0, nbins) self.slider_la.setValue(st_la) self.slider_la.setTracking(True) self.slider_la.valueChanged.connect(self.on_draw) #int self.sbox_la = QDoubleSpinBox() self.sbox_la.setSingleStep(la_max / nsbox) self.sbox_la.setFocusPolicy(Qt.StrongFocus) self.sbox_la.setFixedWidth(sbox_len) self.sbox_la.setRange(0, la_max) self.sbox_la.setValue(la_max * st_la * 1.0 / nbins) self.slider_la.valueChanged.connect(self.update_sbox_la) self.sbox_la.editingFinished.connect(self.update_slider_la) #------- self.slider_label_rh = QLabel("R<sub>half</sub>") self.slider_rh = QSlider(Qt.Horizontal) self.slider_rh.setFocusPolicy(Qt.StrongFocus) self.slider_rh.setFixedWidth(slider_len) self.slider_rh.setRange(0, nbins) self.slider_rh.setValue(st_rh) self.slider_rh.setTracking(True) self.slider_rh.valueChanged.connect(self.on_draw) #int self.sbox_rh = QDoubleSpinBox() self.sbox_rh.setSingleStep(rh_max / nsbox) self.sbox_rh.setFocusPolicy(Qt.StrongFocus) self.sbox_rh.setFixedWidth(sbox_len) self.sbox_rh.setRange(0, rh_max) self.sbox_rh.setValue(rh_max * st_rh * 1.0 / nbins) self.slider_rh.valueChanged.connect(self.update_sbox_rh) self.sbox_rh.editingFinished.connect(self.update_slider_rh) #------- self.slider_label_y1 = QLabel("y<sub>1</sub>") self.slider_y1 = QSlider(Qt.Horizontal) self.slider_y1.setFocusPolicy(Qt.StrongFocus) self.slider_y1.setFixedWidth(slider_len) self.slider_y1.setRange(0, nbins) self.slider_y1.setValue(st_y1) self.slider_y1.setTracking(True) self.slider_y1.valueChanged.connect(self.on_draw) #int self.sbox_y1 = QDoubleSpinBox() self.sbox_y1.setSingleStep((y1_max - y1_min) / nsbox) self.sbox_y1.setFocusPolicy(Qt.StrongFocus) self.sbox_y1.setFixedWidth(sbox_len) self.sbox_y1.setRange(y1_min, y1_max) self.sbox_y1.setValue(st_y1 * dps + y1_min) self.slider_y1.valueChanged.connect(self.update_sbox_y1) self.sbox_y1.editingFinished.connect(self.update_slider_y1) #------- self.slider_label_y2 = QLabel("y<sub>2</sub>") self.slider_y2 = QSlider(Qt.Horizontal) self.slider_y2.setFocusPolicy(Qt.StrongFocus) self.slider_y2.setFixedWidth(slider_len) self.slider_y2.setRange(0, nbins) self.slider_y2.setValue(st_y2) self.slider_y2.setTracking(True) self.slider_y2.valueChanged.connect(self.on_draw) #int self.sbox_y2 = QDoubleSpinBox() self.sbox_y2.setSingleStep((y2_max - y2_min) / nsbox) self.sbox_y2.setFocusPolicy(Qt.StrongFocus) self.sbox_y2.setFixedWidth(sbox_len) self.sbox_y2.setRange(y2_min, y2_max) self.sbox_y2.setValue(st_y2 * dps + y2_min) self.slider_y2.valueChanged.connect(self.update_sbox_y2) self.sbox_y2.editingFinished.connect(self.update_slider_y2) #------- self.slider_label_qs = QLabel("q<sub>src</sub>") self.slider_qs = QSlider(Qt.Horizontal) self.slider_qs.setFocusPolicy(Qt.StrongFocus) self.slider_qs.setFixedWidth(slider_len) self.slider_qs.setRange(0, nbins) self.slider_qs.setValue(st_qs) self.slider_qs.setTracking(True) self.slider_qs.valueChanged.connect(self.on_draw) #int self.sbox_qs = QDoubleSpinBox() self.sbox_qs.setSingleStep(qs_max / nsbox) self.sbox_qs.setFocusPolicy(Qt.StrongFocus) self.sbox_qs.setFixedWidth(sbox_len) self.sbox_qs.setRange(0.0, qs_max) self.sbox_qs.setValue(qs_max * st_qs * 1.0 / nbins) self.slider_qs.valueChanged.connect(self.update_sbox_qs) self.sbox_qs.editingFinished.connect(self.update_slider_qs) #------- self.slider_label_sa = QLabel(u'\u03b8' "<sub>src</sub>") self.slider_sa = QSlider(Qt.Horizontal) self.slider_sa.setFocusPolicy(Qt.StrongFocus) self.slider_sa.setFixedWidth(slider_len) self.slider_sa.setRange(0, nbins) self.slider_sa.setValue(st_sa) self.slider_sa.setTracking(True) self.slider_sa.valueChanged.connect(self.on_draw) #int self.sbox_sa = QDoubleSpinBox() self.sbox_sa.setSingleStep(sa_max / nsbox) self.sbox_sa.setFocusPolicy(Qt.StrongFocus) self.sbox_sa.setFixedWidth(sbox_len) self.sbox_sa.setRange(0.0, sa_max) self.sbox_sa.setValue(sa_max * st_sa * 1.0 / nbins) self.slider_sa.valueChanged.connect(self.update_sbox_sa) self.sbox_sa.editingFinished.connect(self.update_slider_sa) #------- # # Layout with box sizers # hbox = QHBoxLayout() for w in [ self.sbox_label_h0, self.sbox_h0, self.sbox_label_om, self.sbox_om, self.sbox_label_ol, self.sbox_ol, self.cb_cosmo, self.cb_models, self.cb_codes, self.draw_button ]: # for w in [self.cb_cosmo, self.sbox_h0, self.sbox_om, self.sbox_ol, self.cb_models, self.cb_codes, self.draw_button]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) # hbox.setAlignment(w, Qt.AlignRight) # hbox.setAlignment(w, Qt.AlignJustify) vbox = QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) hbox_s1 = QHBoxLayout() for w in [ self.slider_label_re, self.sbox_re, self.slider_re, self.slider_label_rh, self.sbox_rh, self.slider_rh ]: hbox_s1.addWidget(w) hbox_s1.setAlignment(w, Qt.AlignLeft) hbox_s2 = QHBoxLayout() for w in [ self.slider_label_x1, self.sbox_x1, self.slider_x1, self.slider_label_y1, self.sbox_y1, self.slider_y1 ]: hbox_s2.addWidget(w) hbox_s2.setAlignment(w, Qt.AlignLeft) hbox_s3 = QHBoxLayout() for w in [ self.slider_label_x2, self.sbox_x2, self.slider_x2, self.slider_label_y2, self.sbox_y2, self.slider_y2 ]: hbox_s3.addWidget(w) hbox_s3.setAlignment(w, Qt.AlignLeft) hbox_s4 = QHBoxLayout() for w in [ self.slider_label_ql, self.sbox_ql, self.slider_ql, self.slider_label_qs, self.sbox_qs, self.slider_qs ]: hbox_s4.addWidget(w) hbox_s4.setAlignment(w, Qt.AlignLeft) hbox_s5 = QHBoxLayout() for w in [ self.slider_label_la, self.sbox_la, self.slider_la, self.slider_label_sa, self.sbox_sa, self.slider_sa ]: hbox_s5.addWidget(w) hbox_s5.setAlignment(w, Qt.AlignLeft) vbox.addLayout(hbox) vbox.addLayout(hbox_s1) vbox.addLayout(hbox_s2) vbox.addLayout(hbox_s3) vbox.addLayout(hbox_s4) vbox.addLayout(hbox_s5) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame)
date_format = r"%Y-%m-%dT%H:%M:%S" dates = [] users = set() n_points = 1000 with open(list_name) as f: current_list = json.load(f) for d, u in current_list: users.add(u['id']) dates.append(datetime.strptime(d, date_format)) L = len(dates) print('Total users:', L) dates = np.array(sorted(dates), dtype='M8[us]') dt = (dates[-1] - dates[0]) // n_points X = np.arange(dates[0], dates[-1] + dt, dt) Y = np.array([(dates <= x).sum() for x in X]) fmt = mdates.DateFormatter('%m/%d') ax = pylab.axes() ax.xaxis.set_major_formatter(fmt) pylab.title('NuCypher KMS') # pylab.semilogy(X.astype(datetime), Y, linewidth=2) pylab.plot(X.astype(datetime), Y, linewidth=2) pylab.xlabel('Date') pylab.ylabel('Telegram users') pylab.show()
tpoints = arange(t0, t1, h) xpoints = [] ypoints = [] r = array([1.49e11, 0.0, 0.0, 29800.0], float) #r = array([1.49e11, 0.0, 0.0, 20800.0],float) for t in tpoints: xpoints.append(r[0]) ypoints.append(r[1]) k1 = h * f(r, t) k2 = h * f(r + 0.5 * k1, t + 0.5 * h) k3 = h * f(r + 0.5 * k2, t + 0.5 * h) k4 = h * f(r + k3, t + h) r += (k1 + 2 * k2 + 2 * k3 + k4) / 6.0 xau = [x / 1.496e11 for x in xpoints] yau = [y / 1.496e11 for y in ypoints] #plot(xpoints, ypoints) plot(xau, yau) axes().set_aspect('equal', 'datalim') xlim(-1.5, 1.5) ylim(-1.5, 1.5) xlabel("x (AU)") ylabel("y (AU)") #grid(2.0) show()
#------------------------------------------------ # Plot the magnitude response of the filter. #------------------------------------------------ figure(2) clf() w, h = freqz(taps, worN=8000) plot((w / pi) * nyq_rate, absolute(h), linewidth=2) xlabel('Frequency (Hz)') ylabel('Gain') title('Frequency Response') ylim(-0.05, 1.05) grid(True) # Upper inset plot. ax1 = axes([0.42, 0.6, .45, .25]) plot((w / pi) * nyq_rate, absolute(h), linewidth=2) xlim(0, 8.0) ylim(0.9985, 1.001) grid(True) # Lower inset plot ax2 = axes([0.42, 0.25, .45, .25]) plot((w / pi) * nyq_rate, absolute(h), linewidth=2) xlim(12.0, 20.0) ylim(0.0, 0.0025) grid(True) #------------------------------------------------ # Plot the original and filtered signals. #------------------------------------------------
#for sat in satSystem.sats: # a.add_patch( mp.patches.Circle( #print "plotting clumps with trajectories ... " #for i in range(clumps.noc): # curtraj = clumps.traj[i] # a.add_patch( mp.patches.Circle((curtraj[0,2], curtraj[0,0]), radius=clumps.rc[i], ec='yellow', fc='none', lw=0.3, alpha=0.3) ) # a.add_patch( mp.patches.Circle((curtraj[-1,2], curtraj[-1,0]), radius=clumps.rc[i], ec='green', fc='none', lw=0.3, alpha=0.6) ) # a.plot( curtraj[:,2], curtraj[:,0], color='white', lw=0.3, alpha=0.3) # a.text( curtraj[0,2], curtraj[0,0], '$\mathrm{'+ '%1.4f' % ( clumps.m[i] / Mearth ) +' M_{\earth}}$', size=3, color='yellow') # #a.text( curtraj[0,2], curtraj[0,0], ' '+ '%1.4f' % ( clumps.m[i] / Mearth ) +' Me', size=3, color='yellow') pl.figure(figsize=(3, 2)) #a = pl.axes( [0.0, 0.0, 1.0, 1.0], axisbg='k') a = pl.axes([0.1, 0.1, 0.9, 0.9]) pl.grid(True) a.axis("scaled") a.axis([-8.e9, 4.e9, -5.e9, 3.e9]) #for cursat in satSystem.sats: # cursat.plotorbit(a) # a.add_patch( mp.patches.Circle((cursat.r0m[0], cursat.r0m[1]), radius=cursat.rc, ec='green', fc='none', lw=1.0, alpha=0.6) ) M = 1. m = 0. rM = np.array([0.0, 0., 0.]) #rm = np.array( [1.5, 0., 0.0] ) #rm = np.array( [0.7071, 0.0000, -0.7071] ) #rm = np.array( [0.7071, 0.7071, -0.0000] )
setp(bp['fliers'][0], color='blue') # setp(bp['fliers'][1], color='blue') setp(bp['medians'][0], color='blue') setp(bp['boxes'][1], color='red') setp(bp['caps'][2], color='red') setp(bp['caps'][3], color='red') setp(bp['whiskers'][2], color='red') setp(bp['whiskers'][3], color='red') # setp(bp['fliers'][2], color='red') # setp(bp['fliers'][3], color='red') setp(bp['medians'][1], color='red') fig = figure() ax = axes() hold(True) # Some fake data to plot # A = [p, [7, 2]] # B = [q, [7, 2, 5]] # C = [[3, 2, 5, 7], [6, 7, 3]] # # A = [p, [7, 2]] # B = [q, [7, 2, 5]] # C = [[3, 2, 5, 7], [6, 7, 3]] A = [p[0], q[0]] B = [p[1], q[1]] C = [p[2], q[2]]
def plot(): fig = pl.figure(num='Fig. 4: Suppression scenarios', figsize=(figw, figh)) rx = 0.07 r1y = 0.74 rdx = 0.26 r1dy = 0.20 rδ = 0.30 r1δy = 0.29 r1ax = {} for i in range(6): xi = i % 3 yi = i // 3 r1ax[i] = pl.axes([rx + rδ * xi, r1y - r1δy * yi, rdx, r1dy]) r2y = 0.05 r2dy = rdx * figw / figh # To ensure square r2ax = {} for i in range(3): r2ax[i] = pl.axes([rx + rδ * i, r2y, rdx, r2dy]) cax = pl.axes([0.96, r2y, 0.01, r2dy]) # Labels lx = 0.015 pl.figtext(lx, r1y + r1dy + 0.02, 'a', fontsize=40) pl.figtext(lx, r2y + r2dy + 0.02, 'b', fontsize=40) slopes = sc.objdict().make(keys=df1map.keys(), vals=[]) slopes2 = sc.objdict().make(keys=df1map.keys(), vals=[]) for plotnum, key, label in df1map.enumitems(): cv.set_seed(plotnum) ax = r1ax[plotnum] for ei in eis: theseinds = sc.findinds(~np.isnan(df1[key].values)) if sepinds: ei_ok = sc.findinds(df1['eind'].values == ei) theseinds = np.intersect1d(theseinds, ei_ok) x = xvals[key][theseinds] rawy = df1[ykey].values[theseinds] y = rawy / kcpop * 100 if logy else rawy xm = x.max() if key in ['testdelay', 'trtime']: xnoise = 0.01 ynoise = 0.05 else: xnoise = 0 ynoise = 0 rndx = (np.random.randn(len(x))) * xm * xnoise rndy = (np.random.randn(len(y))) * ynoise ax.scatter(x + rndx, y * (1 + rndy), alpha=0.2, c=[cols[ei]], edgecolor='w') # Calculate slopes slopey = np.log(rawy) if logy else rawy slopex = xvals[key].values[theseinds] tmp, res = np.polyfit(slopex, slopey, 1, cov=True) fitm, fitb = tmp factor = np.exp(fitm * slopepoint[key] + fitb) / slopedenom[key] * slopex.max() slope = fitm * factor slopes[key].append(slope) # Calculate slopes, method 2 -- used for std calculation X = sm.add_constant(slopex) mod = sm.OLS(slopey, X) res = mod.fit() conf = res.conf_int(alpha=0.05, cols=None) best = res.params[1] * factor high = conf[1, 1] * factor slopes2[key].append(res) # Plot fit line bflx = np.array([x.min(), x.max()]) ploty = np.log10(y) if logy else y plotm, plotb = np.polyfit(x, ploty, 1) bfly = plotm * bflx + plotb if logy: ax.semilogy(bflx, 10**(bfly), lw=3, c=c2) else: ax.plot(bflx, bfly, lw=3, c=c2) plot_baseinds = False if plot_baseinds: default_x = default_xvals[key][baseinds] default_rawy = df1[ykey].values[baseinds] default_y = default_rawy / kcpop * 100 if logy else default_rawy ax.scatter(default_x, default_y, marker='x', alpha=1.0, c=[cols[i]]) if verbose: print( f'Slope for {key:10s}: {np.mean(slopes[key]):0.3f} ± {high-best:0.3f}' ) sc.boxoff(ax=ax) ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter()) if plotnum in [0, 3]: if logy: ax.set_ylabel('Attack rate (%)') ax.set_yticks((0.01, 0.1, 1.0, 10, 100)) ax.set_yticklabels(('0.01', '0.1', '1.0', '10', '100')) else: ax.set_ylabel(r'$R_{e}$') ax.set_xlabel(xlabelmap[key]) if key in ['iqfactor']: ax.set_xticks(np.linspace(0, 100, 6)) elif key in ['trprob']: ax.set_xticks(np.linspace(0, 10, 6)) elif key in ['testprob']: ax.set_xticks(np.arange(7)) elif key in ['testqprob']: ax.set_xticks(np.arange(7)) else: ax.set_xticks(np.arange(8)) if logy: ax.set_ylim([0.1, 100]) else: ax.set_ylim([0.7, 1.7]) xl = ax.get_xlim() if logy: ypos1 = 150 ypos2 = 40 else: ypos1 = 1.9 ypos2 = 1.7 xlpos = dict( iqfactor=0.86, testprob=0.13, trprob=0.83, testqprob=0.86, testdelay=0.13, trtime=0.00, ) if key in ['iqfactor', 'testqprob', 'trprob']: align = 'right' else: align = 'left' ax.text((xl[0] + xl[1]) / 2, ypos1, label, fontsize=26, horizontalalignment='center') ax.text(xlpos[key] * xl[1], ypos2, f'{abs(best):0.2f} ± {high-best:0.2f} {slopelabels[key]}', color=pointcolor, horizontalalignment=align) ax.axvline(slopepoint[key], ymax=0.83, linestyle='--', c=pointcolor, alpha=0.5, lw=2) reop = [0.6, 0.8, 1.0] for ri, r in enumerate(reop): dfr = df2[df2['reopen'] == r] im = plot_surface(r2ax[ri], dfr, col=ri, colval=r) bbox = dict(facecolor='w', alpha=0.0, edgecolor='none') pointsize = 150 if ri == 0: dotx = 1900 * 1000 / kcpop doty = 0.06 r2ax[ri].scatter([dotx], [doty], c='k', s=pointsize, zorder=10, marker='d') r2ax[ri].text(dotx * 1.20, doty * 1.50, 'Estimated\nconditions\non June 1', bbox=bbox) if ri == 1: dotx = 3000 * 1000 / kcpop doty = 0.20 r2ax[ri].scatter([dotx], [doty], c=[pointcolor2], s=pointsize, zorder=10, marker='d') r2ax[ri].text(dotx * 1.10, doty * 0.20, 'Estimated\nconditions\non July 15', color=pointcolor2, bbox=bbox) if ri == 2: dotx = 2.80 # 7200*1000/kcpop doty = 0.70 # 0.66 r2ax[ri].scatter([dotx], [doty], c=[pointcolor], s=pointsize, zorder=10, marker='d') r2ax[ri].text(dotx * 1.05, doty * 1.05, 'High mobility,\nhigh test + trace\nscenario', color=pointcolor, bbox=bbox) cbar = pl.colorbar(im, ticks=np.linspace(0.4, 1.6, 7), cax=cax) cbar.ax.set_title('$R_{e}$', rotation=0, pad=20, fontsize=24) return fig
def plot_scatter_plus_marginals(x, y, sColor='k', xColor='k', yColor='k', xlim=None, ylim=None): """ Makes a scatter plot of 2D data along with marginal densities in each coordinate, drawn using kernel density estimates. Parameters: ------------- x : 1D array-like object y : 1D array-like object sColor : string, optional color for scatterplot points xColor : string, optional color for KDE(x) yColor : string, optional color for KDE(y) xlim : list, optional x limits for plot; computed from x if none provided ylim : list, optional y limits for plot; computed from y if None """ # axis formatter def my_formatter(x, pos): return '%2.2f' % x # kde/limits kdepoints = 512 inflation = 0.25 # compute axis limits if not provided if xlim is None: xlim = [0, 0] xlim[0] = min(x) - inflation * abs(min(x)) xlim[1] = max(x) + inflation * abs(max(x)) if ylim is None: ylim = [0, 0] ylim[0] = min(y) - inflation * abs(min(y)) ylim[1] = max(y) + inflation * abs(max(y)) # plot and axis locations left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.05 mainCoords = [left, bottom, width, height] xHistCoords = [left, bottom_h, width, 0.2] yHistCoords = [left_h, bottom, 0.2, height] f = pylab.figure(1, figsize=(8, 8)) # scatter plot axMain = pylab.axes(mainCoords, frameon=False) axMain.scatter(x, y, c=sColor, marker='o', alpha=0.5) axMain.set_xlim(xlim) axMain.set_ylim(ylim) axMain.get_xaxis().set_visible(False) axMain.get_yaxis().set_visible(False) # x histogram axxHist = pylab.axes(xHistCoords, frameon=False) axxHist.get_yaxis().set_visible(False) kdex = gaussian_kde(x) xsupport = linspace(xlim[0], xlim[1], kdepoints) mPDF = kdex(xsupport) axxHist.plot(xsupport, mPDF, xColor, lw=3) # add axis line, clean up axxHist.plot(xlim, [0, 0], 'k-', lw=3) axxHist.set_xlim(xlim) axxHist.set_xticks(xlim) axxHist.tick_params(axis='x', direction='in', top=False) axxHist.xaxis.set_major_formatter(FuncFormatter(my_formatter)) axxHist.set_yticks([]) # y histogram axyHist = pylab.axes(yHistCoords, frameon=False) axyHist.get_xaxis().set_visible(False) kdey = gaussian_kde(y) ysupport = linspace(ylim[0], ylim[1], kdepoints) mPDF = kdey(ysupport) axyHist.plot(mPDF, ysupport, yColor, lw=3) # add axis line, clean up axyHist.plot([0, 0], ylim, 'k-', lw=3) axyHist.set_ylim(ylim) axyHist.set_yticks(ylim) axyHist.tick_params(axis='y', direction='in', right=False) axyHist.yaxis.set_major_formatter(FuncFormatter(my_formatter)) axyHist.set_xticks([]) return axMain
U = points['U'] point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K'] path = [G, X, U, L, G, K] path_kc, q, Q = get_bandpath(path, atoms.cell, 100) omega_kn = 1000 * ph.band_structure(path_kc) # DOS omega_e, dos_e = ph.dos(kpts=(50, 50, 50), npts=5000, delta=1e-4) omega_e *= 1000 # Plot phonon dispersion import pylab as plt plt.figure(1, (8, 6)) plt.axes([.1, .07, .67, .85]) for n in range(len(omega_kn[0])): omega_n = omega_kn[:, n] plt.plot(q, omega_n, 'k-', lw=2) plt.xticks(Q, point_names, fontsize=18) plt.yticks(fontsize=18) plt.xlim(q[0], q[-1]) plt.ylim(0, 35) plt.ylabel("Frequency ($\mathrm{meV}$)", fontsize=22) plt.grid('on') plt.axes([.8, .07, .17, .85]) plt.fill_between(dos_e, omega_e, y2=0, color='lightgrey', edgecolor='k', lw=2) plt.ylim(0, 35) plt.xticks([], [])
'verticalalignment': 'bottom' }, transform=axes[label].transAxes) """ 1D network """ ax = axes['A'] ax.yaxis.set_ticks_position('none') ax.xaxis.set_ticks_position('none') ax.spines['bottom'].set_color('none') ax.spines['left'].set_color('none') ax.set_xticks([]) ax.set_yticks([]) ax_inset = pl.axes([0.39, .76, 0.1, .05]) ax_inset.yaxis.set_ticks_position('none') ax_inset.xaxis.set_ticks_position('none') ax_inset.set_xticks([0, 10000]) ax_inset.set_xticklabels([0, r'$10^5$']) ax_inset.set_xlim([0., 10000]) ax_inset.set_yticks([0, 500]) ax_inset.set_ylim([0, 500]) ax_inset.tick_params(axis='x', labelsize=4, pad=1) ax_inset.tick_params(axis='y', labelsize=4, pad=1) x = np.arange(0, 150., 1.) """ Panel C (top): Transfer function for three cases: - normal network
def plot_worker(jobq, pid, conc_file): concObj = mfb.MT3D_Concentration(seawat.nlay, seawat.nrow, seawat.ncol, conc_file) ctimes = concObj.get_time_list() while True: args = jobq.get() if args == None: break '''args[0] = plot name args[1] = conc seekpoint args[2] = conc layer to plot args[3] = active reaches args[4] = active wells args[5] = fig_title ''' fig_name = args[0] conc_seekpoint = args[1] lay_idxs = args[2] lines = args[3] wells = args[4] fig_title = args[5] totim, kstp, kper, c, success = concObj.get_array(conc_seekpoint) c = np.ma.masked_where(c <= 0.014, c) fig = pylab.figure(figsize=(8, 8)) ax1 = pylab.axes((0.05, 0.525, 0.45, 0.45)) ax2 = pylab.axes((0.05, 0.055, 0.45, 0.45)) ax3 = pylab.axes((0.525, 0.525, 0.45, 0.45)) ax4 = pylab.axes((0.525, 0.055, 0.45, 0.45)) cax1 = pylab.axes((0.05, 0.53, 0.45, 0.015)) cax2 = pylab.axes((0.05, 0.05, 0.45, 0.015)) cax3 = pylab.axes((0.525, 0.53, 0.45, 0.015)) cax4 = pylab.axes((0.525, 0.05, 0.45, 0.015)) print np.max(c[lay_idxs[1], :, :]) print np.min(c[lay_idxs[1], :, :]) p1 = ax1.imshow(c[lay_idxs[0], :, :], extent=imshow_extent, cmap=cmap, interpolation='none', vmax=1.0, vmin=0.0) p2 = ax2.imshow(c[lay_idxs[1], :, :], extent=imshow_extent, cmap=cmap, interpolation='none', vmax=1.0, vmin=0.0) p3 = ax3.imshow(c[lay_idxs[2], :, :], extent=imshow_extent, cmap=cmap, interpolation='none', vmax=1.0, vmin=0.0) p4 = ax4.imshow(c[lay_idxs[3], :, :], extent=imshow_extent, cmap=cmap, interpolation='none', vmax=1.0, vmin=0.0) cb1 = pylab.colorbar(p1, cax=cax1, orientation='horizontal') cb2 = pylab.colorbar(p2, cax=cax2, orientation='horizontal') cb3 = pylab.colorbar(p3, cax=cax3, orientation='horizontal') cb4 = pylab.colorbar(p4, cax=cax4, orientation='horizontal') cb1.set_label('Concentration ' + seawat.layer_botm_names[lay_idxs[0]]) cb2.set_label('Concentration ' + seawat.layer_botm_names[lay_idxs[1]]) cb3.set_label('Concentration ' + seawat.layer_botm_names[lay_idxs[2]]) cb4.set_label('Concentration ' + seawat.layer_botm_names[lay_idxs[3]]) ax1.set_ylim(flow.plt_y) ax1.set_xlim(flow.plt_x) ax2.set_ylim(flow.plt_y) ax2.set_xlim(flow.plt_x) ax3.set_ylim(flow.plt_y) ax3.set_xlim(flow.plt_x) ax4.set_ylim(flow.plt_y) ax4.set_xlim(flow.plt_x) ax1.set_xticklabels([]) ax3.set_xticklabels([]) ax3.set_yticklabels([]) ax4.set_yticklabels([]) #-- plot active reaches for line in lines: ax1.plot(line[0, :], line[1, :], 'k-', lw=0.25) ax2.plot(line[0, :], line[1, :], 'k-', lw=0.25) ax3.plot(line[0, :], line[1, :], 'k-', lw=0.25) ax4.plot(line[0, :], line[1, :], 'k-', lw=0.25) #-- plot active wells #for wpoint in wells: # color=salt_well_color # if hds_name: # ax1.plot(wpoint[0],wpoint[1],'.',mfc=color,mec='none',ms=4) # ax2.plot(wpoint[0],wpoint[1],'.',mfc=color,mec='none',ms=4) # if zta_name: # ax3.plot(wpoint[0],wpoint[1],'.',mfc=color,mec='none',ms=4) # ax4.plot(wpoint[0],wpoint[1],'.',mfc=color,mec='none',ms=4) for wpoint in wells: color = 'k' ax1.plot(wpoint[0], wpoint[1], '.', mfc=color, mec='none', ms=4) ax2.plot(wpoint[0], wpoint[1], '.', mfc=color, mec='none', ms=4) ax3.plot(wpoint[0], wpoint[1], '.', mfc=color, mec='none', ms=4) ax4.plot(wpoint[0], wpoint[1], '.', mfc=color, mec='none', ms=4) fig.text(0.5, 0.965, fig_title, ha='center') pylab.savefig(fig_name, dpi=300, format='png', bbox_inches='tight') pylab.close('all') print pid, '-- done--', fig_title jobq.task_done() jobq.task_done() return
#!/usr/bin/env python # -*- coding: utf-8 -*- import Numeric as num from gpaw import GPAW from gpaw.spherical_harmonics import Y a = 6.0 c = a / 2 d = 1.13 paw = GPAW('co.gpw', txt=None) import pylab as p dpi = 2 * 80 p.figure(figsize=(4, 3), dpi=dpi) p.axes([0.15, 0.15, 0.8, 0.8]) import sys if len(sys.argv) == 1: N = 1 else: N = int(sys.argv[1]) psit = paw.kpt_u[0].psit_nG[N] psit = psit[:, 0, 0] ng = len(psit) x = num.arange(ng) * a / ng - c p.plot(x, psit, 'bx', mew=2, label=r'$\tilde{\psi}$') C = 'g' for n in paw.nuclei: s = n.setup phi_j, phit_j = s.get_partial_waves()[:2] print s.rcut_j[0]
def plot_points_plus_kde(xlist, labels, markx=False, lines=3, size=9, ax=None): """ Accepts a list of one-dimensional densities and plots each as points on a line with a KDE on top. Parameters: ------------- xlist : list of array-like objects data to produce density plot for labels : list of legend labels; len(labels) should equal len(xlist) markx : bool, optional put tick labels at the min/max values in x? lines : integer, optional line/marker edge thickness size : integer, optional marker size color : string, optional color for points and kde ax : pylab axes object, optional """ if ax is None: ax = pylab.axes(frameon=False) # cycles through colors cw = color_wheel(lines=('-'), symbols=('o')) for i in xrange(0, len(xlist)): # spin the color wheel (c, s, l) = cw.next() # make the point plot ax.plot(xlist[i], zeros(xlist[i].shape), c + s, markersize=size, mew=lines, alpha=0.5) # kde kde = gaussian_kde(xlist[i]) lpoint = min(xlist[i]) - 0.025 * abs(min(xlist[i])) rpoint = max(xlist[i]) + 0.025 * abs(max(xlist[i])) support = linspace(lpoint, rpoint, 512) mPDF = kde(support) ax.plot(support, mPDF, color=c, lw=lines, label=labels[i]) # prtty things up ax.get_yaxis().set_visible(False) ax.set_ylim(bottom=-0.1) if markx: major_formatter = pylab.FormatStrFormatter('%1.2f') ax.get_xaxis().set_major_formatter(major_formatter) ax.get_xaxis().tick_bottom() minx = min([min(x) for x in xlist]) maxx = max([max(x) for x in xlist]) ax.get_xaxis().set_ticks([minx, maxx]) else: ax.get_xaxis().set_ticks([]) # legend ax.legend(loc='best') return ax
def recreate_image(codebook, labels, w, h): """Recreate the (compressed) image from the code book & labels""" d = codebook.shape[1] image = np.zeros((w, h, d)) label_idx = 0 for i in range(w): for j in range(h): image[i][j] = codebook[labels[label_idx]] label_idx += 1 return image # Display all results, alongside original image pl.figure(1) pl.clf() ax = pl.axes([0, 0, 1, 1]) pl.axis('off') pl.title('Original image (96,615 colors)') pl.imshow(china) pl.figure(2) pl.clf() ax = pl.axes([0, 0, 1, 1]) pl.axis('off') pl.title('Quantized image (64 colors, K-Means)') pl.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h)) pl.figure(3) pl.clf() ax = pl.axes([0, 0, 1, 1]) pl.axis('off')
## Scatter plot: import pylab as plb x = plb.rand(1, 2, 1500) print(x) y = plb.rand(1, 2, 1500) plb.axes([0.075, 0.075, 0.88, 0.88]) plb.cla() plb.scatter(x, y, s=65, alpha=.75, linewidth=0.125, c=plb.arctan2(x, y)) plb.grid(True) plb.xlim(-0.085, 1.085), plb.ylim(-0.085, 1.085) #plb.pause(1) plb.show()
def plot_all(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, kurtosis=True, **kwargs): """ Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future. Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz logged (bool): Plot in linear (False) or dB units (True), t (int): integration number to plot (0 -> len(data)) logged (bool): Plot in linear (False) or dB units (True) if_id (int): IF identification (if multiple IF signals in file) kwargs: keyword args to be passed to matplotlib plot() and imshow() """ if self.header[b'nbits'] <=2: logged = False nullfmt = NullFormatter() # no labels # definitions for the axes left, width = 0.35, 0.5 bottom, height = 0.45, 0.5 width2, height2 = 0.1125, 0.15 bottom2, left2 = bottom - height2 - .025, left - width2 - .02 bottom3, left3 = bottom2 - height2 - .025, 0.075 rect_waterfall = [left, bottom, width, height] rect_colorbar = [left + width, bottom, .025, height] rect_spectrum = [left, bottom2, width, height2] rect_min_max = [left, bottom3, width, height2] rect_timeseries = [left + width, bottom, width2, height] rect_kurtosis = [left3, bottom3, 0.25, height2] rect_header = [left3 - .05, bottom, 0.2, height] # -------- # axColorbar = plt.axes(rect_colorbar) # print 'Ploting Colorbar' # print plot_data.max() # print plot_data.min() # # plot_colorbar = range(plot_data.min(),plot_data.max(),int((plot_data.max()-plot_data.min())/plot_data.shape[0])) # plot_colorbar = np.array([[plot_colorbar],[plot_colorbar]]) # # plt.imshow(plot_colorbar,aspect='auto', rasterized=True, interpolation='nearest',) # axColorbar.xaxis.set_major_formatter(nullfmt) # axColorbar.yaxis.set_major_formatter(nullfmt) # heatmap = axColorbar.pcolor(plot_data, edgecolors = 'none', picker=True) # plt.colorbar(heatmap, cax = axColorbar) # -------- axMinMax = plt.axes(rect_min_max) print('Plotting Min Max') self.plot_spectrum_min_max(logged=logged, f_start=f_start, f_stop=f_stop, t=t) plt.title('') axMinMax.yaxis.tick_right() axMinMax.yaxis.set_label_position("right") # -------- axSpectrum = plt.axes(rect_spectrum,sharex=axMinMax) print('Plotting Spectrum') self.plot_spectrum(logged=logged, f_start=f_start, f_stop=f_stop, t=t) plt.title('') axSpectrum.yaxis.tick_right() axSpectrum.yaxis.set_label_position("right") plt.xlabel('') # axSpectrum.xaxis.set_major_formatter(nullfmt) plt.setp(axSpectrum.get_xticklabels(), visible=False) # -------- axWaterfall = plt.axes(rect_waterfall,sharex=axMinMax) print('Plotting Waterfall') self.plot_waterfall(f_start=f_start, f_stop=f_stop, logged=logged, cb=False) plt.xlabel('') # no labels # axWaterfall.xaxis.set_major_formatter(nullfmt) plt.setp(axWaterfall.get_xticklabels(), visible=False) # -------- axTimeseries = plt.axes(rect_timeseries) print('Plotting Timeseries') self.plot_time_series(f_start=f_start, f_stop=f_stop, orientation='v') axTimeseries.yaxis.set_major_formatter(nullfmt) # axTimeseries.xaxis.set_major_formatter(nullfmt) # -------- # Could exclude since it takes much longer to run than the other plots. if kurtosis: axKurtosis = plt.axes(rect_kurtosis) print('Plotting Kurtosis') self.plot_kurtosis(f_start=f_start, f_stop=f_stop) # -------- axHeader = plt.axes(rect_header) print('Plotting Header') # Generate nicer header telescopes = {0: 'Fake data', 1: 'Arecibo', 2: 'Ooty', 3: 'Nancay', 4: 'Parkes', 5: 'Jodrell', 6: 'GBT', 8: 'Effelsberg', 10: 'SRT', 64: 'MeerKAT', 65: 'KAT7' } telescope = telescopes.get(self.header[b"telescope_id"], self.header[b"telescope_id"]) plot_header = "%14s: %s\n" % ("TELESCOPE_ID", telescope) for key in (b'SRC_RAJ', b'SRC_DEJ', b'TSTART', b'NCHANS', b'NBEAMS', b'NIFS', b'NBITS'): try: plot_header += "%14s: %s\n" % (key, self.header[key.lower()]) except KeyError: pass fch1 = "%6.6f MHz" % self.header[b'fch1'] foff = (self.header[b'foff'] * 1e6 * u.Hz) if np.abs(foff) > 1e6 * u.Hz: foff = str(foff.to('MHz')) elif np.abs(foff) > 1e3 * u.Hz: foff = str(foff.to('kHz')) else: foff = str(foff.to('Hz')) plot_header += "%14s: %s\n" % ("FCH1", fch1) plot_header += "%14s: %s\n" % ("FOFF", foff) plt.text(0.05, .95, plot_header, ha='left', va='top', wrap=True) axHeader.set_facecolor('white') axHeader.xaxis.set_major_formatter(nullfmt) axHeader.yaxis.set_major_formatter(nullfmt)
def keppixseries(infile, outfile, plotfile, plottype, filter, function, cutoff, clobber, verbose, logfile, status, cmdLine=False): # input arguments status = 0 seterr(all="ignore") # log the call hashline = '----------------------------------------------------------------------------' kepmsg.log(logfile, hashline, verbose) call = 'KEPPIXSERIES -- ' call += 'infile=' + infile + ' ' call += 'outfile=' + outfile + ' ' call += 'plotfile=' + plotfile + ' ' call += 'plottype=' + plottype + ' ' filt = 'n' if (filter): filt = 'y' call += 'filter=' + filt + ' ' call += 'function=' + function + ' ' call += 'cutoff=' + str(cutoff) + ' ' overwrite = 'n' if (clobber): overwrite = 'y' call += 'clobber=' + overwrite + ' ' chatter = 'n' if (verbose): chatter = 'y' call += 'verbose=' + chatter + ' ' call += 'logfile=' + logfile kepmsg.log(logfile, call + '\n', verbose) # start time kepmsg.clock('KEPPIXSERIES started at', logfile, verbose) # test log file logfile = kepmsg.test(logfile) # clobber output file if clobber: status = kepio.clobber(outfile, logfile, verbose) if kepio.fileexists(outfile): message = 'ERROR -- KEPPIXSERIES: ' + outfile + ' exists. Use --clobber' status = kepmsg.err(logfile, message, verbose) # open TPF FITS file if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \ kepio.readTPF(infile,'TIME',logfile,verbose) if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \ kepio.readTPF(infile,'TIMECORR',logfile,verbose) if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \ kepio.readTPF(infile,'CADENCENO',logfile,verbose) if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \ kepio.readTPF(infile,'FLUX',logfile,verbose) if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \ kepio.readTPF(infile,'FLUX_ERR',logfile,verbose) if status == 0: kepid, channel, skygroup, module, output, quarter, season, \ ra, dec, column, row, kepmag, xdim, ydim, qual, status = \ kepio.readTPF(infile,'QUALITY',logfile,verbose) # read mask defintion data from TPF file if status == 0: maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition( infile, logfile, verbose) # print target data if status == 0: print('') print(' KepID: %s' % kepid) print(' RA (J2000): %s' % ra) print('Dec (J2000): %s' % dec) print(' KepMag: %s' % kepmag) print(' SkyGroup: %2s' % skygroup) print(' Season: %2s' % str(season)) print(' Channel: %2s' % channel) print(' Module: %2s' % module) print(' Output: %1s' % output) print('') # how many quality = 0 rows? if status == 0: npts = 0 nrows = len(fluxpixels) for i in range(nrows): if qual[i] == 0 and \ numpy.isfinite(barytime[i]) and \ numpy.isfinite(fluxpixels[i,ydim*xdim/2]): npts += 1 time = empty((npts)) timecorr = empty((npts)) cadenceno = empty((npts)) quality = empty((npts)) pixseries = empty((ydim, xdim, npts)) errseries = empty((ydim, xdim, npts)) # construct output light curves if status == 0: np = 0 for i in range(ydim): for j in range(xdim): npts = 0 for k in range(nrows): if qual[k] == 0 and \ numpy.isfinite(barytime[k]) and \ numpy.isfinite(fluxpixels[k,ydim*xdim/2]): time[npts] = barytime[k] timecorr[npts] = tcorr[k] cadenceno[npts] = cadno[k] quality[npts] = qual[k] pixseries[i, j, npts] = fluxpixels[k, np] errseries[i, j, npts] = errpixels[k, np] npts += 1 np += 1 # define data sampling if status == 0 and filter: tpf, status = kepio.openfits(infile, 'readonly', logfile, verbose) if status == 0 and filter: cadence, status = kepkey.cadence(tpf[1], infile, logfile, verbose) tr = 1.0 / (cadence / 86400) timescale = 1.0 / (cutoff / tr) # define convolution function if status == 0 and filter: if function == 'boxcar': filtfunc = numpy.ones(numpy.ceil(timescale)) elif function == 'gauss': timescale /= 2 dx = numpy.ceil(timescale * 10 + 1) filtfunc = kepfunc.gauss() filtfunc = filtfunc([1.0, dx / 2 - 1.0, timescale], linspace(0, dx - 1, dx)) elif function == 'sinc': dx = numpy.ceil(timescale * 12 + 1) fx = linspace(0, dx - 1, dx) fx = fx - dx / 2 + 0.5 fx /= timescale filtfunc = numpy.sinc(fx) filtfunc /= numpy.sum(filtfunc) # pad time series at both ends with noise model if status == 0 and filter: for i in range(ydim): for j in range(xdim): ave, sigma = kepstat.stdev(pixseries[i, j, :len(filtfunc)]) padded = numpy.append(kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \ numpy.ones(len(filtfunc)) * sigma), pixseries[i,j,:]) ave, sigma = kepstat.stdev(pixseries[i, j, -len(filtfunc):]) padded = numpy.append(padded, kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \ numpy.ones(len(filtfunc)) * sigma)) # convolve data if status == 0: convolved = convolve(padded, filtfunc, 'same') # remove padding from the output array if status == 0: outdata = convolved[len(filtfunc):-len(filtfunc)] # subtract low frequencies if status == 0: outmedian = median(outdata) pixseries[i, j, :] = pixseries[i, j, :] - outdata + outmedian # construct output file if status == 0 and ydim * xdim < 1000: instruct, status = kepio.openfits(infile, 'readonly', logfile, verbose) status = kepkey.history(call, instruct[0], outfile, logfile, verbose) hdulist = HDUList(instruct[0]) cols = [] cols.append( Column(name='TIME', format='D', unit='BJD - 2454833', disp='D12.7', array=time)) cols.append( Column(name='TIMECORR', format='E', unit='d', disp='E13.6', array=timecorr)) cols.append( Column(name='CADENCENO', format='J', disp='I10', array=cadenceno)) cols.append(Column(name='QUALITY', format='J', array=quality)) for i in range(ydim): for j in range(xdim): colname = 'COL%d_ROW%d' % (i + column, j + row) cols.append( Column(name=colname, format='E', disp='E13.6', array=pixseries[i, j, :])) hdu1 = new_table(ColDefs(cols)) try: hdu1.header.update('INHERIT', True, 'inherit the primary header') except: status = 0 try: hdu1.header.update('EXTNAME', 'PIXELSERIES', 'name of extension') except: status = 0 try: hdu1.header.update( 'EXTVER', instruct[1].header['EXTVER'], 'extension version number (not format version)') except: status = 0 try: hdu1.header.update('TELESCOP', instruct[1].header['TELESCOP'], 'telescope') except: status = 0 try: hdu1.header.update('INSTRUME', instruct[1].header['INSTRUME'], 'detector type') except: status = 0 try: hdu1.header.update('OBJECT', instruct[1].header['OBJECT'], 'string version of KEPLERID') except: status = 0 try: hdu1.header.update('KEPLERID', instruct[1].header['KEPLERID'], 'unique Kepler target identifier') except: status = 0 try: hdu1.header.update('RADESYS', instruct[1].header['RADESYS'], 'reference frame of celestial coordinates') except: status = 0 try: hdu1.header.update('RA_OBJ', instruct[1].header['RA_OBJ'], '[deg] right ascension from KIC') except: status = 0 try: hdu1.header.update('DEC_OBJ', instruct[1].header['DEC_OBJ'], '[deg] declination from KIC') except: status = 0 try: hdu1.header.update('EQUINOX', instruct[1].header['EQUINOX'], 'equinox of celestial coordinate system') except: status = 0 try: hdu1.header.update('TIMEREF', instruct[1].header['TIMEREF'], 'barycentric correction applied to times') except: status = 0 try: hdu1.header.update('TASSIGN', instruct[1].header['TASSIGN'], 'where time is assigned') except: status = 0 try: hdu1.header.update('TIMESYS', instruct[1].header['TIMESYS'], 'time system is barycentric JD') except: status = 0 try: hdu1.header.update('BJDREFI', instruct[1].header['BJDREFI'], 'integer part of BJD reference date') except: status = 0 try: hdu1.header.update('BJDREFF', instruct[1].header['BJDREFF'], 'fraction of the day in BJD reference date') except: status = 0 try: hdu1.header.update('TIMEUNIT', instruct[1].header['TIMEUNIT'], 'time unit for TIME, TSTART and TSTOP') except: status = 0 try: hdu1.header.update('TSTART', instruct[1].header['TSTART'], 'observation start time in BJD-BJDREF') except: status = 0 try: hdu1.header.update('TSTOP', instruct[1].header['TSTOP'], 'observation stop time in BJD-BJDREF') except: status = 0 try: hdu1.header.update('LC_START', instruct[1].header['LC_START'], 'mid point of first cadence in MJD') except: status = 0 try: hdu1.header.update('LC_END', instruct[1].header['LC_END'], 'mid point of last cadence in MJD') except: status = 0 try: hdu1.header.update('TELAPSE', instruct[1].header['TELAPSE'], '[d] TSTOP - TSTART') except: status = 0 try: hdu1.header.update('LIVETIME', instruct[1].header['LIVETIME'], '[d] TELAPSE multiplied by DEADC') except: status = 0 try: hdu1.header.update('EXPOSURE', instruct[1].header['EXPOSURE'], '[d] time on source') except: status = 0 try: hdu1.header.update('DEADC', instruct[1].header['DEADC'], 'deadtime correction') except: status = 0 try: hdu1.header.update('TIMEPIXR', instruct[1].header['TIMEPIXR'], 'bin time beginning=0 middle=0.5 end=1') except: status = 0 try: hdu1.header.update('TIERRELA', instruct[1].header['TIERRELA'], '[d] relative time error') except: status = 0 try: hdu1.header.update('TIERABSO', instruct[1].header['TIERABSO'], '[d] absolute time error') except: status = 0 try: hdu1.header.update('INT_TIME', instruct[1].header['INT_TIME'], '[s] photon accumulation time per frame') except: status = 0 try: hdu1.header.update('READTIME', instruct[1].header['READTIME'], '[s] readout time per frame') except: status = 0 try: hdu1.header.update('FRAMETIM', instruct[1].header['FRAMETIM'], '[s] frame time (INT_TIME + READTIME)') except: status = 0 try: hdu1.header.update('NUM_FRM', instruct[1].header['NUM_FRM'], 'number of frames per time stamp') except: status = 0 try: hdu1.header.update('TIMEDEL', instruct[1].header['TIMEDEL'], '[d] time resolution of data') except: status = 0 try: hdu1.header.update('DATE-OBS', instruct[1].header['DATE-OBS'], 'TSTART as UTC calendar date') except: status = 0 try: hdu1.header.update('DATE-END', instruct[1].header['DATE-END'], 'TSTOP as UTC calendar date') except: status = 0 try: hdu1.header.update('BACKAPP', instruct[1].header['BACKAPP'], 'background is subtracted') except: status = 0 try: hdu1.header.update('DEADAPP', instruct[1].header['DEADAPP'], 'deadtime applied') except: status = 0 try: hdu1.header.update('VIGNAPP', instruct[1].header['VIGNAPP'], 'vignetting or collimator correction applied') except: status = 0 try: hdu1.header.update('GAIN', instruct[1].header['GAIN'], '[electrons/count] channel gain') except: status = 0 try: hdu1.header.update('READNOIS', instruct[1].header['READNOIS'], '[electrons] read noise') except: status = 0 try: hdu1.header.update('NREADOUT', instruct[1].header['NREADOUT'], 'number of read per cadence') except: status = 0 try: hdu1.header.update('TIMSLICE', instruct[1].header['TIMSLICE'], 'time-slice readout sequence section') except: status = 0 try: hdu1.header.update('MEANBLCK', instruct[1].header['MEANBLCK'], '[count] FSW mean black level') except: status = 0 hdulist.append(hdu1) hdulist.writeto(outfile) status = kepkey.new('EXTNAME', 'APERTURE', 'name of extension', instruct[2], outfile, logfile, verbose) pyfits.append(outfile, instruct[2].data, instruct[2].header) status = kepio.closefits(instruct, logfile, verbose) else: message = 'WARNING -- KEPPIXSERIES: output FITS file requires > 999 columns. Non-compliant with FITS convention.' kepmsg.warn(logfile, message) # plot style if status == 0: try: params = { 'backend': 'png', 'axes.linewidth': 2.0, 'axes.labelsize': 32, 'axes.font': 'sans-serif', 'axes.fontweight': 'bold', 'text.fontsize': 8, 'legend.fontsize': 8, 'xtick.labelsize': 12, 'ytick.labelsize': 12 } pylab.rcParams.update(params) except: pass # plot pixel array fmin = 1.0e33 fmax = -1.033 if status == 0: pylab.figure(num=None, figsize=[12, 12]) pylab.clf() dx = 0.93 / xdim dy = 0.94 / ydim ax = pylab.axes([0.06, 0.05, 0.93, 0.94]) pylab.gca().xaxis.set_major_formatter( pylab.ScalarFormatter(useOffset=False)) pylab.gca().yaxis.set_major_formatter( pylab.ScalarFormatter(useOffset=False)) pylab.gca().xaxis.set_major_locator( matplotlib.ticker.MaxNLocator(integer=True)) pylab.gca().yaxis.set_major_locator( matplotlib.ticker.MaxNLocator(integer=True)) labels = ax.get_yticklabels() setp(labels, 'rotation', 90, fontsize=12) pylab.xlim(numpy.min(pixcoord1) - 0.5, numpy.max(pixcoord1) + 0.5) pylab.ylim(numpy.min(pixcoord2) - 0.5, numpy.max(pixcoord2) + 0.5) pylab.xlabel('time', {'color': 'k'}) pylab.ylabel('arbitrary flux', {'color': 'k'}) for i in range(ydim): for j in range(xdim): tmin = amin(time) tmax = amax(time) try: numpy.isfinite(amin(pixseries[i, j, :])) numpy.isfinite(amin(pixseries[i, j, :])) fmin = amin(pixseries[i, j, :]) fmax = amax(pixseries[i, j, :]) except: ugh = 1 xmin = tmin - (tmax - tmin) / 40 xmax = tmax + (tmax - tmin) / 40 ymin = fmin - (fmax - fmin) / 20 ymax = fmax + (fmax - fmin) / 20 if kepstat.bitInBitmap(maskimg[i, j], 2): pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy], axisbg='lightslategray') elif maskimg[i, j] == 0: pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy], axisbg='black') else: pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy]) if j == int(xdim / 2) and i == 0: pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[]) elif j == 0 and i == int(ydim / 2): pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[]) else: pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[]) ptime = time * 1.0 ptime = numpy.insert(ptime, [0], ptime[0]) ptime = numpy.append(ptime, ptime[-1]) pflux = pixseries[i, j, :] * 1.0 pflux = numpy.insert(pflux, [0], -1000.0) pflux = numpy.append(pflux, -1000.0) pylab.plot(time, pixseries[i, j, :], color='#0000ff', linestyle='-', linewidth=0.5) if not kepstat.bitInBitmap(maskimg[i, j], 2): pylab.fill(ptime, pflux, fc='lightslategray', linewidth=0.0, alpha=1.0) pylab.fill(ptime, pflux, fc='#FFF380', linewidth=0.0, alpha=1.0) if 'loc' in plottype: pylab.xlim(xmin, xmax) pylab.ylim(ymin, ymax) if 'glob' in plottype: pylab.xlim(xmin, xmax) pylab.ylim(1.0e-10, numpy.nanmax(pixseries) * 1.05) if 'full' in plottype: pylab.xlim(xmin, xmax) pylab.ylim(1.0e-10, ymax * 1.05) # render plot if cmdLine: pylab.show() else: pylab.ion() pylab.plot([]) pylab.ioff() if plotfile.lower() != 'none': pylab.savefig(plotfile) # stop time if status == 0: kepmsg.clock('KEPPIXSERIES ended at', logfile, verbose) return
from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, 45, 10] explode = (0, 0.05, 0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True) title('Users', bbox={'facecolor': '0.8', 'pad': 5}) savefig('foo.png') show() # Actually, don't show, just save to foo.png
#17. Save these steps in a .py file and email it to me before next class. I will run it! plb.show() """ LECTURE ADVANCED PLOTTING """ #Bar plot import pylab as plb k = 8 x = plb.arange(k) y1 = plb.rand(k)*(1-x/k) y2 = plb.rand(k) * (1-x/k) plb.axes([0.075, 0.075, .88, .88]) plb.bar(x, +y1, facecolor='#9922aa', edgecolor='green') plb.bar(x, -y2, facecolor='#ff3366', edgecolor='green') for a, b in zip(x, y1): plb.text(a+0.41, b+0.08, '%.3f' % b, ha='center', va='bottom') for a, b in zip(x, y2): plb.text(a+0.41, -b-0.08, '%.3f' % b, ha='center', va='bottom') plb.xlim(-.5, k), plb.ylim(-1.12, +1.12) plb.grid(True) plb.show() # Scatter plot x = plb.rand(1,2,1500)
def interferometer_mod(run, calib, s1=[], s2=[], scope='2', diam=0.155575, showPlot=False, writeFiles=False): """Interferometer analysis routine. Reads data from the altered cosine/sine data and runs the analysis. Inputting a proper diameter is necessary. Diameter is path length of interferometer in cm. In oblate flux conservers it should be 50 cm. For neck part of oblate conservers, it should be 15.5575 cm. calib should be a tuple/list of the maximum and minimums observed on the scope for each channel at the beginning of the run day.""" data = sdr.scope_data(run, scope) names = ['signal1', 'signal2'] channels = (1, 2) mult = (1, 1) units = ('arb', 'arb') data.setScopeProperties(names, channels, mult) data.calib = dict(zip(names, calib)) if s1 == []: dv1 = data.signal1 - np.mean(data.signal1[0:10]) else: dv1 = s1 - np.mean(s1[0:10]) if s2 == []: dv2 = data.signal2 - np.mean(data.signal2[0:10]) else: dv2 = s2 - np.mean(s2[0:10]) arg = 1 - 0.5 * ((dv1 / data.calib[names[0]])**2 + (dv2 / data.calib[names[1]])**2) #remove values outside of arccos domain spikes = np.where(arg < -1.0) arg[spikes] = -1.0 dphi = np.arccos(arg) data.dphi = dphi # .155575 m is the ID of the small part of the flux conserver # mks #density = (dphi * 4 * pi * (3e8)**2 * 8.854e-12 * 9.109e-31) / #((1.602e-19)**2 * 632.8e-9 * .155575) #cgs #density = (dphi * (3e10)**2 * 9.109e-28) / ((4.8032e-10)**2 * 632.8e-7 * # diam) density = 5.62e14 * dphi / diam data.pathlength = diam data.density = density if showPlot or writeFiles: fig = figure(13, **ssxdef.f) fig.clear() a = axes() a.plot(data.time, data.density, 'k-') xlabel('Time (us)') ylabel('Density (#/cm$^3$)') title(data.shotname) if writeFiles: # make output directory fName = ssxutil.ssxPath( 'interferometer.png', 'output', data.runYear + '/' + data.runDate + '/' + run) dir, trash = os.path.split(fName) os.spawnlp(os.P_WAIT, 'mkdir', 'mkdir', '-p', dir) fig.savefig(fName) else: show() x1, x2 = data.signal1, data.signal2 k1, k2 = calib[0], calib[1] error = (3.6 * 10**15) * 0.00627 * (x1 * (k1**-2) + x2 * (k2**-2)) / np.sqrt(4 * ((x1 / k1)**2 + (x2 / k2)**2) - ((x1 / k1)**2 + (x2 / k2)**2)**2) return data, error
def verbose_plot(Z, Xp): """create a nice verbose plot based on the a set of indicator samples Z Z: n x XR : array of indicator vectors of mixture responsibilities Xp: X-coordinates for evaluation of predictive distributions """ #get predictions from the indicators: B = predictIndicator(Z, Xp) #mean bernoulli Bm = B.mean(axis=0) #mean of indicators Zm = Z.mean(axis=0) > 0.5 IS = Zm IJ = ~Zm #updata datasets self.gpr_0.setData(S.concatenate((M0R[0][:, IS]), axis=0).reshape([-1, 1]), S.concatenate((M0R[1][:, IS]), axis=1), process=False) self.gpr_1.setData(S.concatenate((M1R[0][:, IS]), axis=0).reshape([-1, 1]), S.concatenate((M1R[1][:, IS]), axis=1), process=False) self.gpr_join.setData(S.concatenate((MJR[0][:, IJ]), axis=0).reshape([-1, 1]), S.concatenate((MJR[1][:, IJ]), axis=1), process=False) #now plot stuff PL.clf() ax1 = PL.axes([0.15, 0.1, 0.8, 0.7]) #plot marginal GP predictions alpha = 0.18 self.plotGPpredict_gradient(self.gpr_0, M0, Xp, Bm, { 'alpha': alpha, 'facecolor': 'r' }, { 'linewidth': 2, 'color': 'r' }) self.plotGPpredict_gradient(self.gpr_1, M0, Xp, Bm, { 'alpha': alpha, 'facecolor': 'g' }, { 'linewidth': 2, 'color': 'g' }) self.plotGPpredict_gradient(self.gpr_join, M0, Xp, (1 - Bm), { 'alpha': alpha, 'facecolor': 'b' }, { 'linewidth': 2, 'color': 'b' }) PL.plot(M0[0].T, M0[1].T, 'r.--') PL.plot(M1[0].T, M1[1].T, 'g.--') #set xlim PL.xlim([Xp.min(), Xp.max()]) yticks = ax1.get_yticks()[0:-2] ax1.set_yticks(yticks) xlabel('Time/days') ylabel('Log expression level') Ymax = MJ[1].max() Ymin = MJ[1].min() DY = Ymax - Ymin PL.ylim([Ymin - 0.1 * DY, Ymax + 0.1 * DY]) #2nd. plot prob. of diff ax2 = PL.axes([0.15, 0.8, 0.8, 0.10], sharex=ax1) PL.plot(Xp, Bm, 'k-', linewidth=2) ylabel('$P(z(t)=1)$') # PL.yticks([0.0,0.5,1.0]) PL.yticks([0.5]) #horizontal bar PL.axhline(linewidth=0.5, color='#aaaaaa', y=0.5) PL.ylim([0, 1]) setp(ax2.get_xticklabels(), visible=False) pass
def vuvLookupCurve(ratio, showPlot=False): """Takes ratio of 97/155 lines and returns T_e at 3 densities. 1 density for now (5e14). Added in the factor of 5 senstivity from MacPherson. Data from below: ----- 97over155 columns: 1: T (ev) 2: 97/155 ratio for ne=1e14 3: 97/155 ratio for ne=5e14 4: 97/155 ratio for ne=2e15 5 63.8344 69.25164 9.979064 10 0.1552918 0.09093285 0.05106842 15 0.03828019 0.02603559 0.01611151 20 0.01610708 0.01156093 0.00755031 25 0.008135443 0.00604283 0.00407848 30 0.004953774 0.00376594 0.002603922 35 0.003384 0.002619757 0.001845273 40 0.002494533 0.001958196 0.001399227 45 0.001939878 0.001539707 0.00111413 50 0.001568844 0.00125666 9.193383E-4 55 0.001307071 0.001054908 7.789212E-4 60 0.001114454 9.052276E-4 6.737394E-4 65 9.631904E-4 7.868332E-4 5.8992E-4 70 8.449692E-4 6.937241E-4 5.231481E-4 75 7.504907E-4 6.188965E-4 4.691748E-4 80 6.73543E-4 5.576425E-4 4.248821E-4 85 6.098714E-4 5.067226E-4 3.877307E-4 90 5.564431E-4 4.638157E-4 3.564039E-4 95 5.110662E-4 4.272359E-4 3.293811E-4 100 4.721179E-4 3.957284E-4 3.062352E-4 # """ data = array( [[ 5.00000000e+00, 1.00000000e+01, 1.50000000e+01, 2.00000000e+01, 2.50000000e+01, 3.00000000e+01, 3.50000000e+01, 4.00000000e+01, 4.50000000e+01, 5.00000000e+01, 5.50000000e+01, 6.00000000e+01, 6.50000000e+01, 7.00000000e+01, 7.50000000e+01, 8.00000000e+01, 8.50000000e+01, 9.00000000e+01, 9.50000000e+01, 1.00000000e+02 ], [ 6.38344000e+01, 1.55291800e-01, 3.82801900e-02, 1.61070800e-02, 8.13544300e-03, 4.95377400e-03, 3.38400000e-03, 2.49453300e-03, 1.93987800e-03, 1.56884400e-03, 1.30707100e-03, 1.11445400e-03, 9.63190400e-04, 8.44969200e-04, 7.50490700e-04, 6.73543000e-04, 6.09871400e-04, 5.56443100e-04, 5.11066200e-04, 4.72117900e-04 ], [ 6.92516400e+01, 9.09328500e-02, 2.60355900e-02, 1.15609300e-02, 6.04283000e-03, 3.76594000e-03, 2.61975700e-03, 1.95819600e-03, 1.53970700e-03, 1.25666000e-03, 1.05490800e-03, 9.05227600e-04, 7.86833200e-04, 6.93724100e-04, 6.18896500e-04, 5.57642500e-04, 5.06722600e-04, 4.63815700e-04, 4.27235900e-04, 3.95728400e-04 ], [ 9.97906400e+00, 5.10684200e-02, 1.61115100e-02, 7.55031000e-03, 4.07848000e-03, 2.60392200e-03, 1.84527300e-03, 1.39922700e-03, 1.11413000e-03, 9.19338300e-04, 7.78921200e-04, 6.73739400e-04, 5.89920000e-04, 5.23148100e-04, 4.69174800e-04, 4.24882100e-04, 3.87730700e-04, 3.56403900e-04, 3.29381100e-04, 3.06235200e-04 ]]) te = arange(5, 100, .001) logratio = arange(-8.13, 0, .1) rat = np.exp(logratio) x = data[0] xr = x[::-1] y = data[1] z = data[2] w = data[3] data = [y, z, w] # logdata = [np.log(dat) for dat in data] datar = [dat[::-1] for dat in data] splr = [sp.interpolate.splrep(np.log(dat), xr, k=3) for dat in datar] splines = [sp.interpolate.splev(logratio, spl) for spl in splr] # splines = [np.exp(logspline) for logspline in logsplines] # y4, z4, w4 = splines if showPlot: polygon = mlab.poly_between(x, y, w) ioff() f = figure(1, **ssxdef.f) f.clear() a = axes() a.semilogy(y4, rat, 'k-') a.semilogy(z4, rat, 'r-') a.semilogy(w4, rat, 'b-') a.semilogy(x, y, 'ks', hold=1, label='n = 1 x 10^14') # n = 1e14 a.semilogy(x, z, 'ro', label='n = 5 x 10^14') # n = 5e14 a.semilogy(x, w, 'b^', label='n = 2 x 10^15') # n = 2e15 xlabel('T (eV)') ylabel('Line Ratio (97.7/155)') ylim(.0001, 1) xlim(0, 100) a.legend(numpoints=1) f.savefig('lineratios1.pdf') f = figure(2, **ssxdef.f) f.clear() a = axes() a.semilogy(z4, rat, 'k-') a.fill(polygon[0], polygon[1], alpha=.3) a.semilogy(x, z, 'ko') title('Line ratios for n = 5 x 10^14') xlabel('T (eV)') ylabel('Line Ratio (97.7/155)') ylim(.0001, 1) xlim(0, 100) a.text(65, .5, 'upper bound is 1x10^14') a.text(65, .37, 'lower bound is 2x10^15') f.savefig('lineratios2.pdf') show() ion() splz = splr[1] # factor of 5 from sensitivity from macpherson # less sensitive to the 97.7 line, so actual amount of light is 5 times as # much at this wavelength temp = sp.interpolate.splev(np.log(ratio * 5), splz) temp = ma.masked_less(temp, sp.interpolate.splev(np.log(1), splz)) temp = ma.masked_invalid(temp) return temp
# Wavelet transform the data cw=wavelet(A,maxscale,notes,scaling=scaling) scales=cw.getscales() cwt=cw.getdata() # power spectrum pwr=cw.getpower() scalespec=np.sum(pwr,axis=1)/scales # calculate scale spectrum # scales y=cw.fourierwl*scales x=np.arange(Nlo*1.0,Nhi*1.0,1.0) fig=mpl.figure(1) # 2-d coefficient plot ax=mpl.axes([0.4,0.1,0.55,0.4]) mpl.xlabel('Time [s]') plotcwt=np.clip(np.fabs(cwt.real), 0., 1000.) if plotpower2d: plotcwt=pwr im=mpl.imshow(plotcwt,cmap=mpl.cm.jet,extent=[x[0],x[-1],y[-1],y[0]],aspect='auto') #colorbar() if scaling=="log": ax.set_yscale('log') mpl.ylim(y[0],y[-1]) ax.xaxis.set_ticks(np.arange(Nlo*1.0,(Nhi+1)*1.0,100.0)) ax.yaxis.set_ticklabels(["",""]) theposition=mpl.gca().get_position() # data plot ax2=mpl.axes([0.4,0.54,0.55,0.3]) mpl.ylabel('Data') pos=ax.get_position()