def plot_cmc(cmc, ni=200): import matplotlib.pyplot as plt import pylab as P import numpy as np fig = P.figure() fig.suptitle('Acumulative Match Characteristic', fontsize=18, fontweight='bold') P.ylabel('%', fontsize=16) P.xlabel('Rank', fontsize=16) P.xlim(0, ni) P.ylim(0,101) P.xticks(np.arange(0, ni, 10.0)) P.yticks(np.arange(0, 101, 5.0)) xticklabels = P.getp(P.gca(), 'xticklabels') yticklabels = P.getp(P.gca(), 'yticklabels') P.setp(yticklabels, 'color', 'k', fontsize='x-large') P.setp(xticklabels, 'color', 'k', fontsize='x-large') P.grid(True) fig.set_size_inches(19,7) #P.plot(cmc*100) P.plot(cmc*100) fig.savefig('cmc_bf_knn.png') P.show()
def get_chart(data, step): fig = pylab.figure( figsize=[1.5, 1], # Inches dpi=100, # 100 dots per inch, so the resulting buffer is 400x400 pixels ) ax = fig.gca() pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), visible=False) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), visible=False) pylab.setp(pylab.getp(pylab.gca(), 'xgridlines'), 'linestyle', ' ') pylab.setp(pylab.getp(pylab.gca(), 'ygridlines'), 'linestyle', ' ') ax.plot(data) ax.grid(True) targets = dict(left=2, right=2, top=2, bottom=2, hspace=0, wspace=0) fig.canvas.mpl_connect('resize_event', lambda e: adjust_borders(fig, targets)) adjust_borders(fig, targets) ax.plot([step], [data[step]], 'ro') canvas = agg.FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.tostring_rgb() return pygame.image.fromstring(raw_data, canvas.get_width_height(), "RGB")
def plot_cmc(cmc, metodo, fl, nf=50, dx=300, w=10, h=7): import matplotlib.pyplot as plt import pylab as P import numpy as np fig = P.figure() fig.suptitle('Cumulative Match Characteristic', fontsize=18, fontweight='bold') P.title(metodo) P.ylabel('%', fontsize=16) P.xlabel('Rank', fontsize=16) P.xlim(0, nf) P.ylim(0, 101) P.xticks(np.arange(0, nf, dx)) P.yticks(np.arange(0, 101, 5.0)) xticklabels = P.getp(P.gca(), 'xticklabels') yticklabels = P.getp(P.gca(), 'yticklabels') P.setp(yticklabels, 'color', 'k', fontsize='x-large') P.setp(xticklabels, 'color', 'k', fontsize='x-large') P.grid(True) fig.set_size_inches(w, h) #P.plot(cmc*100) P.plot(cmc * 100) fig.savefig(fl) P.show()
def build_cmc(arquivos, mylabels, mystyle, linestyles, metodos): #import matplotlib.pyplot as plt import pylab as P import numpy as np import matplotlib from datetime import datetime matplotlib.rcParams.update({'font.size': 17}) fig = P.figure() fig.suptitle('Cumulative Matching Characteristic', fontsize=18, fontweight='bold') #pos = metodos[0].find('0') #P.title(metodos[0][11:(pos-1)]) P.ylabel('%', fontsize=16) P.xlabel('Rank', fontsize=16) ni = 50 #300 P.xlim(0, ni) P.ylim(0, 101) P.xticks(np.arange(0, ni, 10.0)) P.yticks(np.arange(0, 101, 5.0)) xticklabels = P.getp(P.gca(), 'xticklabels') yticklabels = P.getp(P.gca(), 'yticklabels') P.setp(yticklabels, 'color', 'k', fontsize='x-large') P.setp(xticklabels, 'color', 'k', fontsize='x-large') P.grid(True) fig.set_size_inches(10, 7) for (aq, pt, ls) in zip(arquivos, mystyle, linestyles): #print aq #cmc = np.loadtxt('./BOV_' + aq + '_ASIFT/cmc_bov_' + aq + '_asift.out',delimiter=',') #cmc = np.loadtxt('./FV_' + aq + 'GMM_SIFT/cmc_fv_' + aq + '_sift.out',delimiter=',') cmc = np.loadtxt(aq[0] + aq[1], delimiter=',') P.plot(cmc * 100, pt, label=aq, linewidth=1, ms=10, markevery=5) #, linestyle=ls) #[:-6]) P.legend(bbox_to_anchor=(0.95, 0.5), borderaxespad=0.0, labels=mylabels) #fig.savefig('cmc_SIFT_ASIFT_MHSLCD.png') DT = (datetime.now()).strftime("%Y%m%d%H%M%S") fig.set_size_inches(12, 8) pos = mylabels[0].find('0') if pos <= 0: pos = len(metodos[0]) + 1 fig.savefig('cmc_Mescla_' + DT + '.png', dpi=300, bbox_inches='tight') #fig.savefig('cmc_SIFT_ASIFT_MHSLCD.png', dpi=300, bbox_inches='tight') #fig.savefig('cmc_FV_SIFT.png', dpi=300, bbox_inches='tight') #fig.savefig('cmc_BOV_ASIFT.png', dpi=300, bbox_inches='tight') P.show()
def SetPlot(): ############################ set plot defaults yticklabels = getp(gca(),'yticklabels') xticklabels = getp(gca(),'xticklabels') setp(xticklabels,fontsize='20') setp(yticklabels,fontsize='20') font = FontProperties( size="smaller" ) legend(numpoints=1,markerscale=.8,loc=(1.01,0.0),ncol=1,prop=font ,fancybox=True) leg = gca().get_legend() ltext = leg.get_texts() setp(ltext,fontsize=10)
def enlarge_allticklines(axx, factor=2): '''modify all tick lines in place''' lines = [] for tick in axx.minorTicks: xt = pylab.getp(tick.tick1line, 'ms') pylab.setp(tick.tick2line, ms=xt * factor) xt = pylab.getp(tick.tick2line, 'ms') pylab.setp(tick.tick1line, ms=xt * factor) for tick in axx.majorTicks: xt = pylab.getp(tick.tick1line, 'ms') pylab.setp(tick.tick2line, ms=xt * factor) xt = pylab.getp(tick.tick2line, 'ms') pylab.setp(tick.tick1line, ms=xt * factor)
def decoratePlot(legsize=16,xsize=16,ysize=16): """ Decorating the plots, text-sizes """ if legsize!=0: leg=pylab.gca().get_legend() txt=leg.get_texts() pylab.setp(txt, fontsize=legsize,family=font) xticklabels = pylab.getp(pylab.gca(), 'xticklabels') yticklabels = pylab.getp(pylab.gca(), 'yticklabels') pylab.setp(yticklabels, fontsize=ysize,family=font) pylab.setp(xticklabels, fontsize=xsize,family=font)
def adjust_axis(axn=None, c='r', step=0, side='x', position=True): ''' adjusts position and color of x or y ticks axn = selected axis c = new color for ticks step = layer of offset side = x or y position = True or False True = top or right ''' if axn is None: axn = pylab.gca() pylab.axes(axn) #locator = ticker.AutoLocator() #locator.autoscale() #eval('axn.' + side + 'axis.set_major_locator(locator)') #formatter = ticker.FixedFormatter() #reval('axn.' + side + 'axis.set_major_formatter(formatter)') choose_axes(axn, position=position, side=side) yt = pylab.getp(axn, side + 'ticklabels') ticklabels = pylab.getp(axn, side + 'ticklabels') pylab.setp(ticklabels, 'color', c) pylab.setp(eval('axn.' + side + 'axis.label'), color=c) yt = pylab.getp(axn, side + 'ticklines') pylab.setp(yt, color=c) if step > 0: dpad = 0 dlen = 25 * step if side == 'x' and position: drot = 90 ddir = 1 elif side == 'x': drot = -90 ddir = -1 elif side == 'y' and position: drot = 0 ddir = 1 else: ddir = -1 drot = 180 dpad = -5 eval('axn.' + side + 'axis.get_major_ticks()') ticklabels = pylab.getp(axn, side + 'ticklabels') pylab.setp(ticklabels, dashdirection=ddir, dashlength=dlen, dashrotation=drot, dashpad=dpad) eval('pylab.setp(axn.get_' + side + 'gridlines(),c=\'' + c + '\')') pylab.draw_if_interactive()
def _draw_main_error(self): """ plot the error with respect to the true solution on our optional visualization """ myg = self.grids[self.nlevels - 1].grid v = self.grids[self.nlevels - 1].get_var("v") e = v - self.true_function(myg.x2d, myg.y2d) pylab.imshow(numpy.transpose(e[myg.ilo:myg.ihi + 1, myg.jlo:myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax]) pylab.xlabel("x") pylab.ylabel("y") pylab.title(r"current fine grid error") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize="small")
def _plot_topo_imshow(epochs, show_func, layout, decim, vmin, vmax, colorbar, cmap, layout_scale): """Helper function: plot tfr on sensor layout""" import pylab as pl if cmap is None: cmap = pl.cm.jet ch_names = _clean_names(epochs.info['ch_names']) pl.rcParams['axes.facecolor'] = 'k' fig = pl.figure(facecolor='k') pos = layout.pos.copy() if colorbar: pos[:, :2] *= layout_scale pl.rcParams['axes.edgecolor'] = 'k' sm = pl.cm.ScalarMappable(cmap=cmap, norm=pl.normalize(vmin=vmin, vmax=vmax)) sm.set_array(np.linspace(vmin, vmax)) ax = pl.axes([0.015, 0.025, 1.05, .8], axisbg='k') cb = fig.colorbar(sm, ax=ax) cb_yticks = pl.getp(cb.ax.axes, 'yticklabels') pl.setp(cb_yticks, color='w') pl.rcParams['axes.edgecolor'] = 'w' for idx, name in enumerate(_clean_names(layout.names)): if name in ch_names: ax = pl.axes(pos[idx], axisbg='k') ch_idx = ch_names.index(name) show_func(ax, ch_idx, 1e3 * epochs.times[0], 1e3 * epochs.times[-1], vmin, vmax) pl.xticks([], ()) pl.yticks([], ()) # Revert global pylab config pl.rcParams['axes.facecolor'] = 'w' pl.rcParams['axes.edgecolor'] = 'k' return fig
def plot_clusters(locations, idx, centroids): locations = np.array(locations) print "the cluster labels ", idx plot( locations[idx == 0, 0], locations[idx == 0, 1], "ob", locations[idx == 1, 0], locations[idx == 1, 1], "or", locations[idx == 2, 0], locations[idx == 2, 1], "ok", locations[idx == 3, 0], locations[idx == 3, 1], "oc", locations[idx == 4, 0], locations[idx == 4, 1], "oy", locations[idx == 5, 0], locations[idx == 5, 1], "om", locations[idx == 6, 0], locations[idx == 6, 1], "og", ) plot(centroids[:, 0], centroids[:, 1], "sg", markersize=8) setp(gca(), "ylim", reversed(getp(gca(), "ylim"))) show()
def _draw_solution(self): """ plot the current solution on our optional visualization """ myg = self.grids[self.current_level].grid v = self.grids[self.current_level].get_var("v") pylab.imshow( numpy.transpose(v[myg.ilo : myg.ihi + 1, myg.jlo : myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax], ) # pylab.xlabel("x") pylab.ylabel("y") if self.current_level == self.nlevels - 1: pylab.title(r"solving $L\phi = f$") else: pylab.title(r"solving $Le = r$") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, "ymajorticklabels") pylab.setp(cl, fontsize="small")
def _draw_solution(self): """ plot the current solution on our optional visualization """ myg = self.grids[self.current_level].grid v = self.grids[self.current_level].get_var("v") pylab.imshow(numpy.transpose(v[myg.ilo:myg.ihi + 1, myg.jlo:myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax]) #pylab.xlabel("x") pylab.ylabel("y") if self.current_level == self.nlevels - 1: pylab.title(r"solving $L\phi = f$") else: pylab.title(r"solving $Le = r$") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize="small")
def _draw_main_error(self): """ plot the error with respect to the true solution on our optional visualization """ myg = self.grids[self.nlevels - 1].grid v = self.grids[self.nlevels - 1].get_var("v") e = v - self.true_function(myg.x2d, myg.y2d) pylab.imshow( numpy.transpose(e[myg.ilo : myg.ihi + 1, myg.jlo : myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax], ) pylab.xlabel("x") pylab.ylabel("y") pylab.title(r"current fine grid error") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, "ymajorticklabels") pylab.setp(cl, fontsize="small")
def plot_size_tunning(self, xindex, yindex,independent=True): if independent: fig = pylab.figure() colors=['red','blue','green','purple','orange','black','yellow'] measurment = self.data_dict[(xindex,yindex)]["ST"] i = 0 #m = 0 for curve_label in measurment.keys(): curve = measurment[curve_label]["data"] x_values = sorted(curve.keys()) y_values = [curve[key].view()[0][xindex, yindex] for key in x_values] pylab.plot(x_values, y_values, lw=3, color=colors[i],label=curve_label) m = max(0,max(y_values)) pylab.annotate('', xy=(measurment[curve_label]["measures"]["peak_near_facilitation"], y_values[measurment[curve_label]["measures"]["peak_near_facilitation_index"]]), xycoords='data', xytext=(-1, 20), textcoords='offset points', arrowprops=dict(facecolor='green', shrink=0.05)) if measurment[curve_label]["measures"].has_key("peak_supression"): pylab.annotate('', xy=(measurment[curve_label]["measures"]["peak_supression"], y_values[measurment[curve_label]["measures"]["peak_supression_index"]]), xycoords='data', xytext=(-1, 20), textcoords='offset points', arrowprops=dict(facecolor='red', shrink=0.05)) if measurment[curve_label]["measures"].has_key("peak_far_facilitation"): pylab.annotate('', xy=(measurment[curve_label]["measures"]["peak_far_facilitation"], y_values[measurment[curve_label]["measures"]["peak_far_facilitation_index"]]), xycoords='data', xytext=(-1, 20), textcoords='offset points', arrowprops=dict(facecolor='blue', shrink=0.05)) i+=1 disable_top_right_axis(pylab.gca()) ax = pylab.gca() pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax.set_xticklabels(ax.get_xticks(), fontProperties) ax.set_yticklabels(ax.get_yticks(), fontProperties) ax.set_xlim(0,2) ax.set_xticks([0,1,2]) m = numpy.ceil(m) ax.set_yticks([0,m/2,m]) ax.set_ylim(0,m) if independent: release_fig("STC[" + str(xindex) + "," + str(yindex) + "]")
def my_2D_plot_of_arrays(xa, ya, title, xlabel, ylabel, *add_graphs): fig = plt.figure() ax = fig.add_subplot(111) lines=ax.plot(xa, ya, 'b-o', markersize=2, color="green") line = lines[0] line.set_linewidth( 1.5 ) line.set_color( 'green' ) line.set_linestyle( '-' ) line.set_marker('s') line.set_markerfacecolor('red') line.set_markeredgecolor( '0.1' ) line.set_markersize( 3 ) ## format the ticks adl = mdates.AutoDateLocator() ax.xaxis.set_major_locator(adl) myformatter = MyAutoDateFormatter(adl) #myformatter = mdates.AutoDateFormatter(adl) ax.xaxis.set_major_formatter(myformatter) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) labels = getp(ax, 'xticklabels') setp(labels, color='g', fontsize=9, fontname="Verdana" ) labels = getp(ax, 'yticklabels') setp(labels, color='g', fontsize=9, fontname="Verdana" ) ax.grid(True) fig.autofmt_xdate(bottom=0.18, rotation=60) min_y=min(ya) max_y=max(ya) if (min_y<0) and (max_y >0): ax.axhline(0, color='r', lw=4, alpha=0.5) ax.fill_between(xa, ya, facecolor='red', alpha=0.5, interpolate=True) #plot additional graphs if len(add_graphs): draw_add_2D_plot_of_arrays(add_graphs, ax) plt.show()
def plot_stc_time_point(stc, subject, limits=[5, 10, 15], time_index=0, surf='inflated', measure='dSPM', subjects_dir=None): """Plot a time instant from a SourceEstimate using matplotlib The same could be done with mayavi using proper 3D. Parameters ---------- stc : instance of SourceEstimate The SourceEstimate to plot. subject : string The subject name (only needed if surf is a string). time_index : int Time index to plot. surf : str, or instance of surfaces Surface to use (e.g., 'inflated' or 'white'), or pre-loaded surfaces. measure : str The label for the colorbar. None turns the colorbar off. subjects_dir : str, or None Path to the SUBJECTS_DIR. If None, the path is obtained by using the environment variable SUBJECTS_DIR. """ subjects_dir = get_subjects_dir(subjects_dir) pl.figure(facecolor='k', figsize=(8, 5)) hemis = ['lh', 'rh'] if isinstance(surf, str): surf = [read_surface(op.join(subjects_dir, subject, 'surf', '%s.%s' % (h, surf))) for h in hemis] my_cmap = mne_analyze_colormap(limits) for hi, h in enumerate(hemis): coords = surf[hi][0][stc.vertno[hi]] if hi == 0: vals = stc_all_cluster_vis.lh_data[:, time_index] else: vals = stc_all_cluster_vis.rh_data[:, time_index] ax = pl.subplot(1, 2, 1 - hi, axis_bgcolor='none') pl.tick_params(labelbottom='off', labelleft='off') flipper = -1 if hi == 1 else 1 sc = ax.scatter(flipper * coords[:, 1], coords[:, 2], c=vals, vmin=-limits[2], vmax=limits[2], cmap=my_cmap, edgecolors='none', s=5) ax.set_aspect('equal') pl.axis('off') try: pl.tight_layout(0) except: pass if measure is not None: cax = pl.axes([0.85, 0.15, 0.025, 0.15], axisbg='k') cb = pl.colorbar(sc, cax, ticks=[-limits[2], 0, limits[2]]) cb.set_label(measure, color='w') pl.setp(pl.getp(cb.ax, 'yticklabels'), color='w') pl.draw() pl.show()
def __plot(self, subplot=111, title=None, ylabel=None): self.open_table(self.infile) subt = self.table.query('any(ANTENNA1==%s && ANTENNA2==%s)' % (self.antid, self.antid)) datcol = subt.getcol(self.datacol) flgcol = subt.getcol("FLAG") # only channel flag is needed to be hanled in MS (l,m,n) = datcol.shape if flgcol.shape != (l,m,n): raise Exception, "Data conformation error. Shape of FLAG and %s differs." % self.datacol nrow = subt.nrows() subt.close() self.close_table() pl.ioff() if not ylabel: ylabel = self.datacol for np in range(self.selnpol): pl.ioff() pl.figure(np+1) pl.subplot(subplot) pl.cla() ip = self.selpol if self.selnpol == 1 else np if title: pl.title(self.infile+' Ant:'+ self.antnameused+' '+self.corrtypestr[ip]) datcol2 = datcol[ip].reshape(n) flgcol2 = flgcol[ip].reshape(n) if self.plotlevel > 0: pl.ion() #pl.plot(range(len(datcol2)), datcol2, 'g.') pl.plot(range(len(datcol2)), numpy.ma.masked_array(datcol2, flgcol2), 'g.') pl.xlim(0, nrow) t1 = pl.getp(pl.gca(), 'xticklabels') t2 = pl.getp(pl.gca(), 'yticklabels') pl.setp((t1,t2), fontsize='smaller') pl.ylabel(ylabel, fontsize='smaller') pl.xlabel('row #') pl.draw() if self.plotlevel < 0: outplfile=self.infile.rstrip('/')+'_scans_'+self.corrtypestr[self.selcorrtypeind[np]]+'.eps' pl.savefig(outplfile,format='eps') casalog.post( "Plot was written to %s" % outplfile )
def plot_histograms_of_measures(self): histograms_lc = {} histograms_hc = {} for (xcoord,ycoord) in self.data_dict.keys(): for curve_type in self.data_dict[(xcoord,ycoord)].keys(): if curve_type == "ST": curve_label = "Contrast" else: curve_label = "Contrastsurround" print self.data_dict[(xcoord,ycoord)][curve_type].keys() for measure_name in self.data_dict[(xcoord,ycoord)][curve_type][curve_label + " = " + str(self.high_contrast) + "%"]["measures"].keys(): if not histograms_hc.has_key(curve_type + "_" + measure_name): histograms_hc[curve_type + "_" + measure_name]=[] histograms_hc[curve_type + "_" + measure_name].append(self.data_dict[(xcoord,ycoord)][curve_type][curve_label + " = " + str(self.high_contrast) + "%"]["measures"][measure_name]) for measure_name in self.data_dict[(xcoord,ycoord)][curve_type][curve_label + " = " + str(self.low_contrast) + "%"]["measures"].keys(): if not histograms_lc.has_key(curve_type + "_" + measure_name): histograms_lc[curve_type + "_" + measure_name]=[] histograms_lc[curve_type + "_" + measure_name].append(self.data_dict[(xcoord,ycoord)][curve_type][curve_label + " = " + str(self.low_contrast) + "%"]["measures"][measure_name]) for key in histograms_lc.keys(): if ((len(histograms_lc[key]) != 0) and (len(histograms_hc[key]) != 0)): fig = pylab.figure() #pylab.title(str(numpy.mean(histograms_lc[key])) + "+/-" + str(numpy.std(histograms_lc[key])/ (len(histograms_lc[key])*len(histograms_lc[key]))) + "MeanHC: " + str(numpy.mean(histograms_hc[key])) + "+/-" + str(numpy.std(histograms_hc[key])/ (len(histograms_hc[key])*len(histograms_hc[key]))) , fontsize=12) f = fig.add_subplot(111) mmax = numpy.max([numpy.max(histograms_lc[key]),numpy.max(histograms_hc[key])]) mmin = numpy.min([numpy.min(histograms_lc[key]),numpy.min(histograms_hc[key])]) bins = numpy.arange(mmin-0.01,mmax+0.01,(mmax+0.01-(mmin-0.01))/10.0) if key == 'ST_contrast_dependent_shift': f.hist(histograms_hc[key],bins=bins,color='black',normed=False) else: histograms_lc[key] histograms_hc[key] f.hist((histograms_lc[key],histograms_hc[key]),bins=bins,color=['white','black'],normed=True,label=['Low contrast','High contrast']) f.legend(loc = "upper left") ax = pylab.gca() disable_left_axis(ax) disable_top_right_axis(ax) remove_y_tick_labels() ax.xaxis.set_major_locator(MaxNLocator(4)) pylab.setp(pylab.getp(ax, 'xticklabels'), fontsize=20) #f.axvline(x=numpy.mean(histograms_lc[key]),linewidth=4, color='r') release_fig("Histogram<" + key + ">") print key + "LC mean :" + str(numpy.mean(histograms_lc[key])) print key + "HC mean :" + str(numpy.mean(histograms_hc[key])) else: print "Histogram ", key , " empty!"
def get_chart(data, step): fig = pylab.figure(figsize=[1.5, 1], # Inches dpi=100, # 100 dots per inch, so the resulting buffer is 400x400 pixels ) ax = fig.gca() pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), visible=False) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), visible=False) pylab.setp(pylab.getp(pylab.gca(), 'xgridlines'), 'linestyle', ' ') pylab.setp(pylab.getp(pylab.gca(), 'ygridlines'), 'linestyle', ' ') ax.plot(data) ax.grid(True) targets = dict(left=2, right=2, top=2, bottom=2, hspace=0, wspace=0) fig.canvas.mpl_connect('resize_event', lambda e: adjust_borders(fig, targets)) adjust_borders(fig, targets) ax.plot([step], [data[step]], 'ro') canvas = agg.FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.tostring_rgb() return pygame.image.fromstring(raw_data, canvas.get_width_height(), "RGB")
def hist(train, test, pca=None, xlabel=None): b = _nb_bins(train, 100, 20) _, _, patches = plt.hist(train, bins=b, normed=True, color='gold', label="Train set", alpha=.5) c = plt.getp(patches[0], 'facecolor') vspans(train, c) b = _nb_bins(test, 100, 20) _, _, patches = plt.hist(test, bins=b, normed=True, color='g', label="Test set", alpha=.5) c = plt.getp(patches[0], 'facecolor') vspans(test, c) if not pca is None: b = _nb_bins(pca, 100, 20) _, _, patches = plt.hist(pca, bins=b, normed=True, color='b', label="PCA set", alpha=.5) c = plt.getp(patches[0], 'facecolor') vspans(pca, c) plt.legend(loc="best") plt.grid() plt.xlabel(xlabel)
def click_event(self, event): """Whenever a click occurs on the coefficent axes we modify the coefficents and update the plot""" if event.xdata is None: #we clicked outside the axis return idx = M.getp(event.inaxes, 'label') print idx, event.xdata, event.ydata self.c[idx] = event.xdata self.c[idx + 1] = event.ydata self.replotf() self.replotc()
def click_event(self, event): """Whenever a click occurs on the coefficent axes we modify the coefficents and update the plot""" if event.xdata is None:#we clicked outside the axis return idx = M.getp(event.inaxes,'label') print idx, event.xdata, event.ydata self.c[idx] = event.xdata self.c[idx+1] = event.ydata self.replotf() self.replotc()
def plotConfusion(confusion, grid, title, file_name, inset=None, fudge=16): pylab.figure() axmain = pylab.axes() tick_labels = [ "Missing", "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ] min_label = -1 xs, ys = grid.getXY() pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1)) tick_locs = np.linspace(-1, min_label + len(tick_labels) - 2, len(tick_labels)) tick_locs += (tick_locs[1] - tick_locs[0]) / 2 bar = pylab.colorbar() bar.locator = FixedLocator(tick_locs) bar.formatter = FixedFormatter(tick_labels) pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large') bar.update_ticks() grid.drawPolitical() if inset: lb_y, lb_x = [ b.start for b in inset ] ub_y, ub_x = [ b.stop + fudge for b in inset ] inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x)) axins = zoomed_inset_axes(pylab.gca(), 2, loc=4) pylab.sca(axins) pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1)) grid.drawPolitical() gs_x, gs_y = grid.getGridSpacing() pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x]) pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
xi = +x0 for ii in xrange(Nt): ye[:, ii] = C * xi + D * u[:, ii] xi = A * xi + B * u[:, ii] # plot singular values pylab.figure(1) nsv = 30 a = pylab.semilogy(range(1, nsv + 1), svN[:nsv] / svN[0], '-o', range(1, nsv + 1), sv[:nsv] / sv[0], '-o') pylab.axis([0, nsv, 1e-8, 1]) ax = pylab.gca() pylab.setp(ax, yticks=[1e-8, 1e-6, 1e-4, 1e-2, 1e0]) pylab.xlabel('Singular value index') pylab.ylabel('Normalized singular values') pylab.legend(a, ('Original', 'Optimized'), loc='best') pylab.figure(2) for ii in range(p): pylab.subplot(p, 1, ii + 1) pylab.plot(t.T, y[ii, :].T, t.T, ye[ii, :].T) pylab.hold(True) pylab.plot([N, N], pylab.getp(pylab.gca(), 'ylim')) pylab.hold(False) pylab.xlabel('Time t') pylab.ylabel('Output y' + str(ii)) pylab.legend(a, ('Measured', 'Estimated'), loc='best') pylab.show()
def map_psf_stars(fitsfile, outfile, stars, title, vmin=10, vmax=1500): """ Plot combo image for each field in W51 G48.9-0.3 and overlay the PSF stars. """ datadir = '/u/jlu/data/w51/' outdir = '/u/jlu/work/w51/maps/' ########## # Load the fits file ########## img = pyfits.getdata(fitsfile) ########## # Calculate the coordinates in arcsec ########## scale = 0.00995 # Image extent xaxis = (np.arange(img.shape[0]) - stars[0]['xpix']) * scale * -1.0 yaxis = (np.arange(img.shape[1]) - stars[0]['ypix']) * scale for star in stars: # RA and Dec Offsets (in arcsec) star['x'] = (star['xpix'] - stars[0]['xpix']) * scale * -1.0 star['y'] = (star['ypix'] - stars[0]['ypix']) * scale ########## # Plot Image ########## py.rc('font', **{'weight':'bold'}) py.clf() py.imshow(np.log10(img), cmap=py.cm.YlOrBr_r, vmin=math.log10(vmin), vmax=math.log10(vmax), extent=[xaxis[0], xaxis[-1], yaxis[0], yaxis[-1]]) py.xlabel('R.A. Offset (arcsec)', fontweight='bold') py.ylabel('Dec. Offset (arcsec)', fontweight='bold') py.setp(py.getp(py.gca(), 'xticklabels'), fontweight='bold') py.setp(py.getp(py.gca(), 'yticklabels'), fontweight='bold') py.title(title, fontweight='bold') fig = py.gca() # Draw East/North arrows arr0 = np.array([xaxis[0]-1.7, yaxis[0]+0.3]) arrLen = 1.0 arrColor = 'black' north = py.Arrow(arr0[0], arr0[1], 0, arrLen, width=0.3*arrLen, fill=True, fc=arrColor, ec=arrColor) east = py.Arrow(arr0[0], arr0[1], arrLen, 0, width=0.3*arrLen, fill=True, fc=arrColor, ec=arrColor) fig.add_patch(north) fig.add_patch(east) py.text(arr0[0], arr0[1]+(1.1*arrLen), 'N', color=arrColor, weight='bold', horizontalalignment='center', verticalalignment='bottom') py.text(arr0[0]+(1.1*arrLen), arr0[1], 'E', color=arrColor, weight='bold', horizontalalignment='right', verticalalignment='center') ########## # Plot each PSF star. ########## for star in stars: # Encircle and Label coo star psfRadius = 0.2 psfLabel = '%s\n[%6.3f, %6.3f]' % (star['name'], star['x'], star['y']) psfStar = py.Circle([star['x'], star['y']], radius=psfRadius, fill=False, ec='black', linewidth=3) fig.add_patch(psfStar) py.text(star['x'], star['y']-(1.2*psfRadius), psfLabel, fontweight='bold', color='black', fontsize=10, horizontalalignment='center', verticalalignment='top') # Save py.savefig(outfile) ########## # Generate a PSF star list for Starfinder... only print out to the screen. ########## print '########' print '#' print '# PRINTING PSF starlist for input to Starfinder.' print '# -- paste everything below to a file.' print '# -- example file is /u/jlu/code/idl/w51/psftables/w51a_f1_psf.list' print '#' print '########' print '\n' print '# This file should contain sources we absolutely know exist ' print '# (with names). Additionally, all sources should have velocities ' print '# so that they can be found across multiple epochs. The Filt column ' print '# shows what filters this star should NOT be used in ' print '# (K=speckle, Kp,Lp,Ms = NIRC2). The PSF column specifies whether ' print '# this is a PSF star (1) or just a secondary source (0).' print '#%-12s %-4s %-7s %-7s %-7s %-7s %-8s %-4s %-4s' % \ ('Name', 'Mag', 'Xarc', 'Yarc', 'Vx', 'Vy', 't0', 'Filt', 'PSF?') for star in stars: print '%-13s %4.1f %7.3f %7.3f %7.3f %7.3f %8.3f %-4s %1d' % \ (star['name'], star['mag'], star['x'], star['y'], 0.0, 0.0, 2009.0, '-', 1)
def plotConfusion(confusion, map, grid_spacing, title, file_name, inset=None, fudge=16): pylab.figure() axmain = pylab.axes() gs_x, gs_y = grid_spacing confusion_cmap_dict = { 'red': ( (0.0, 0.5, 0.5), (0.25, 0.5, 1.0), (0.5, 1.0, 0.0), (0.75, 0.0, 1.0), (1.0, 1.0, 1.0), ), 'green': ( (0.0, 0.5, 0.5), (0.25, 0.5, 0.0), (0.5, 0.0, 1.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0), ), 'blue': ( (0.0, 0.5, 0.5), (0.25, 0.5, 1.0), (0.5, 1.0, 0.0), (0.75, 0.0, 1.0), (1.0, 1.0, 1.0), ), } confusion_cmap = LinearSegmentedColormap('confusion', confusion_cmap_dict, 256) nx, ny = confusion.shape xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny)) pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=0, vmax=3) tick_locs = [0.375 + 0.75 * l for l in range(4)] tick_labels = ["Correct\nNegative", "False\nAlarm", "Miss", "Hit"] bar = pylab.colorbar() bar.locator = FixedLocator(tick_locs) bar.formatter = FixedFormatter(tick_labels) pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large') bar.update_ticks() drawPolitical(map, scale_len=25) if inset: lb_y, lb_x = [b.start for b in inset] ub_y, ub_x = [b.stop + fudge for b in inset] inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x)) axins = zoomed_inset_axes(pylab.gca(), 2, loc=4) pylab.sca(axins) pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=0, vmax=3) drawPolitical(map) pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x]) pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
def Figure8(self): self.fig = pylab.figure(facecolor='w',figsize=(14, 12),dpi=800) gs = gridspec.GridSpec(57, 36) gs.update(left=0.05, right=0.95, top=0.95, bottom=0.05,wspace=0.2,hspace=0.2) picked_stcs = [(53,47),(53,49),(55,47),(51,63),(49,53),(47,63)] ax = pylab.subplot(gs[1:19,9:27]) self.plot_average_oct(independent=False) pylab.ylabel('Normalized response', fontsize=20) ax = pylab.subplot(gs[22:32,1:11]) self.plot_orientation_contrast_tuning(picked_stcs[0][0], picked_stcs[0][1],'',independent=False) remove_x_tick_labels() pylab.ylabel('Response', fontsize=20) ax = pylab.subplot(gs[22:32,13:23]) self.plot_orientation_contrast_tuning(picked_stcs[1][0], picked_stcs[1][1],'',independent=False) disable_left_axis(pylab.gca()) remove_x_tick_labels() remove_y_tick_labels() ax = pylab.subplot(gs[22:32,25:35]) self.plot_orientation_contrast_tuning(picked_stcs[2][0], picked_stcs[2][1],'',independent=False) disable_left_axis(pylab.gca()) remove_x_tick_labels() remove_y_tick_labels() ax = pylab.subplot(gs[34:44,1:11]) self.plot_orientation_contrast_tuning(picked_stcs[3][0], picked_stcs[3][1],'',independent=False) pylab.ylabel('Response', fontsize=20) ax = pylab.subplot(gs[34:44,13:23]) self.plot_orientation_contrast_tuning(picked_stcs[4][0], picked_stcs[4][1],'',independent=False) disable_left_axis(pylab.gca()) remove_y_tick_labels() ax = pylab.subplot(gs[34:44,25:35]) self.plot_orientation_contrast_tuning(picked_stcs[5][0], picked_stcs[5][1],'',independent=False) disable_left_axis(pylab.gca()) remove_y_tick_labels() # PLOT EXPERIMENTAL DATA x,y = zip(*[(-88.694, 45.5367),(-81.8258, 45.0061),(-74.9654, 44.2076),(-68.0972, 43.677),(-61.2444, 42.6107),(-54.3686, 42.3479),(-47.5158, 41.2816),(-40.7245, 38.0724),(-34.0868, 29.5059),(-27.4415, 21.2073),(-20.7654, 13.9801),(-13.9357, 12.1102),(-7.006, 13.7225),(0.1156, 22.0313),(7.0299, 23.1078),(13.9364, 23.9165),(20.8891, 26.3325),(27.9186, 31.427),(34.9404, 36.2537),(41.9622, 41.0803),(48.9224, 43.7641),(55.7906, 43.2335),(62.6588, 42.7029),(69.5346, 42.4401),(76.4028, 41.9095), (83.2631, 41.1111),(90.1314, 40.5805)]) ox,oy = zip(*[(-89.7405, 9.108),(-82.8946, 9.3988),(-76.0487, 9.6896),(-69.1876, 10.5161),(-62.3417, 10.8069),(-55.4958, 11.0977),(-48.6423, 11.6562),(-41.7506, 13.5544),(-34.7597, 18.935),(-27.7841, 23.7797),(-20.8008, 28.8923),(-13.8557, 32.6657),(-6.8343, 39.1177),(0.1566, 44.4983),(6.8652, 39.9672),(13.505, 33.0251),(20.183, 27.4224),(26.8686, 22.0877),(33.539, 16.2172),(40.2475, 11.6861),(46.956, 7.155),(53.7942, 7.1779),(60.6172, 6.665),(67.4402, 6.1521),(74.2709, 5.9072),(81.1015, 5.6622),(87.2407, 5.147)]) x = numpy.array(x) y = numpy.array(y) oy = numpy.array(oy) x = x/360.0*numpy.pi*2 ax = pylab.subplot(gs[47:57,5:15]) ax.plot(x,y,lw=3,color='r') ax.plot(x,oy,lw=3,color='b') ax.set_xlim(-numpy.pi/2-0.2,numpy.pi/2.0+0.2) ax.set_xticks([-numpy.pi/2,0,numpy.pi/2.0]) ax.set_ylim(0,50) ax.set_yticks([0,25,50]) ax.set_ylabel('Response', fontsize=20) disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels([r'-$\frac{\pi}{2}$',r'0',r'$\frac{\pi}{2}$'], fontProperties) ax.set_yticklabels(ax.get_yticks(), fontProperties) x,y = zip(*[(-90.5455, 0.6447),(-67.5208, 0.6732),(-45.9417, 0.572),(-22.6714, 0.4924),(-0.5531, 0.3234),(22.8077, 0.5215),(45.0244, 0.6539),(67.7793, 0.7153),(89.9339, 0.6573)]) x = numpy.array(x) y = numpy.array(y) x = x/360.0*numpy.pi*2 ax = pylab.subplot(gs[47:57,19:29]) ax.plot(x,y,lw=3,color='r') ax.set_xlim(-numpy.pi/2-0.2,numpy.pi/2.0+0.2) ax.set_xticks([-numpy.pi/2,0,numpy.pi/2.0]) ax.set_ylim(0,1.0) ax.set_yticks([0,0.5,1.0]) ax.set_ylabel('Relative response', fontsize=20) disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels([r'-$\frac{\pi}{2}$',r'0',r'$\frac{\pi}{2}$'], fontProperties) ax.set_yticklabels(ax.get_yticks(), fontProperties) release_fig("Figure8")
def plotMixtureStructure(mix,headers,transpose=1): plot = numpy.zeros(( mix.G,mix.dist_nr ) ) for i in range(mix.dist_nr): #print "-------------\n",headers[i] #print mix.leaders[i] #print mix.groups[i] # check for noise variables if len(mix.leaders[i]) == 1: l = mix.leaders[i][0] for g in range(mix.G): plot[g,i] = 1 else: for l in mix.leaders[i]: #if len(mix.groups[i][l]) == 0: # plot[l,i] = 2 # else: plot[l,i] = l+3 for g in mix.groups[i][l]: plot[g,i] = l+3 for j in range(mix.dist_nr): t = {} t[2] = 2 t[1] = 1 index = 3 v_list = [] for v in plot[:,j]: if v == 2: continue elif v == 1: break else: if v not in v_list: v_list.append(v) v_list.sort() #print plot[:,j] #print v_list for v in v_list: t[v] = index index +=1 for i in range(mix.G): plot[i,j] = t[plot[i,j]] #for p in plot: # print p.tolist() #print plot #pylab.subplot(1,2,1) #x = numpy.array([0.0,5.0],dtype='Float64') #y = numpy.array([0.0,5.0],dtype='Float64') #pylab.plot(x,y,'o') #pylab.subplot(1,2,2) z = numpy.array(plot) if transpose: #print z.shape z = z.transpose() #print z.shape mat = pylab.matshow(z) # pylab.setp(mat) # print mat.axes # print mat.figure pylab.grid(True,linestyle='-',linewidth=0.5) # set xticks #pylab.xticks( numpy.arange(len(headers))+0.5,['']*len(headers), size=12) xtickpos = numpy.arange(0.0, mix.G+1,0.5) temp = zip(range(mix.G), ['']*mix.G) xticklabels = [] for tt in temp: xticklabels += list(tt) pylab.xticks( xtickpos,xticklabels) # rotation='vertical',size=12 #print xtickpos #print xticklabels # remove grid lines for tick lines at label positions xgridlines = pylab.getp(pylab.gca(), 'xgridlines') #print xgridlines for j in range(len(xticklabels)): if xticklabels[j] != '': xgridlines[j].set_linestyle('None') # set yticks ytickpos = numpy.arange(0.0, len(headers),0.5) temp = zip(headers, ['']*len(headers)) yticklabels = [] for tt in temp: yticklabels += list(tt) pylab.yticks( ytickpos, yticklabels, size=8) # remove grid lines for tick lines at label positions ygridlines = pylab.getp(pylab.gca(), 'ygridlines') #print len(ygridlines), len(ytickpos), len(yticklabels) for j,yl in enumerate(ygridlines): if yticklabels[j] != '': yl.set_linestyle('None') #pylab.setp(ygridlines, 'linestyle', 'None') #pylab.yticks( numpy.arange(len(headers))+0.5) # loc, ll = pylab.yticks() # for lll in ll: # print lll,lll.get_dashlength() # #lll.set_dashlength(-1) #plotMixture.pylab.figtext(0.15,0.5,'T1',size=20, weight='bold') #plotNormalMixtureDensitture.pylab.figtext(0.925,0.5,'T1',size=20, weight='bold') #start = 0.15 # start = 0.18 # end = 0.925 # # space = end - start # step = space / mix.dist_nr #for i in range(0,mix.dist_nr): # XXX HACK for two components #pylab.figtext(0.12,0.63,'$C_1$',size=20, weight='bold') #pylab.figtext(0.12,0.26,'$C_2$',size=20, weight='bold') else: fig = pylab.matshow(z) pylab.grid(True,linestyle='-',linewidth=0.5) #pylab.yticks(numpy.arange(mix.G+1) ) #pylab.xticks( numpy.arange(len(plot[0])+1)+0.5,headers,rotation=90,size=12) #fig.set_size_inches(20,20) # set xticks #pylab.xticks( numpy.arange(len(headers))+0.5,['']*len(headers), size=12) xtickpos = numpy.arange(0.0, len(headers),0.5) temp = zip(headers, ['']*len(headers)) xticklabels = [] for tt in temp: xticklabels += list(tt) pylab.xticks( xtickpos,xticklabels) # rotation='vertical',size=12 print len(xtickpos), xtickpos.tolist() print len(xticklabels), xticklabels # remove grid lines for tick lines at label positions xgridlines = pylab.getp(pylab.gca(), 'xgridlines') print xgridlines for j in range(len(xticklabels)): if xticklabels[j] != '': xgridlines[j].set_linestyle('None') # set yticks ytickpos = numpy.arange(0.0, mix.G,0.5) temp = zip(range(mix.G), ['']*mix.G) yticklabels = [] for tt in temp: yticklabels += list(tt) pylab.yticks( ytickpos, yticklabels, size=12) print len(ytickpos), ytickpos.tolist() print len(yticklabels), yticklabels # remove grid lines for tick lines at label positions ygridlines = pylab.getp(pylab.gca(), 'ygridlines') #print len(ygridlines), len(ytickpos), len(yticklabels) for j,yl in enumerate(ygridlines): if yticklabels[j] != '': yl.set_linestyle('None')
def plot_stc_time_point(stc, subject, limits=[5, 10, 15], time_index=0, surf='inflated', measure='dSPM', subjects_dir=None): """Plot a time instant from a SourceEstimate using matplotlib The same could be done with mayavi using proper 3D. Parameters ---------- stc : instance of SourceEstimate The SourceEstimate to plot. subject : string The subject name (only needed if surf is a string). time_index : int Time index to plot. surf : str, or instance of surfaces Surface to use (e.g., 'inflated' or 'white'), or pre-loaded surfaces. measure : str The label for the colorbar. None turns the colorbar off. subjects_dir : str, or None Path to the SUBJECTS_DIR. If None, the path is obtained by using the environment variable SUBJECTS_DIR. """ subjects_dir = get_subjects_dir(subjects_dir) pl.figure(facecolor='k', figsize=(8, 5)) hemis = ['lh', 'rh'] if isinstance(surf, str): surf = [ read_surface( op.join(subjects_dir, subject, 'surf', '%s.%s' % (h, surf))) for h in hemis ] my_cmap = mne_analyze_colormap(limits) for hi, h in enumerate(hemis): coords = surf[hi][0][stc.vertno[hi]] if hi == 0: vals = stc_all_cluster_vis.lh_data[:, time_index] else: vals = stc_all_cluster_vis.rh_data[:, time_index] ax = pl.subplot(1, 2, 1 - hi, axis_bgcolor='none') pl.tick_params(labelbottom='off', labelleft='off') flipper = -1 if hi == 1 else 1 sc = ax.scatter(flipper * coords[:, 1], coords[:, 2], c=vals, vmin=-limits[2], vmax=limits[2], cmap=my_cmap, edgecolors='none', s=5) ax.set_aspect('equal') pl.axis('off') try: pl.tight_layout(0) except: pass if measure is not None: cax = pl.axes([0.85, 0.15, 0.025, 0.15], axisbg='k') cb = pl.colorbar(sc, cax, ticks=[-limits[2], 0, limits[2]]) cb.set_label(measure, color='w') pl.setp(pl.getp(cb.ax, 'yticklabels'), color='w') pl.draw() pl.show()
pl.gca().set_xticks(inh_range[1::2]) pl.gca().set_xticklabels(inh_range[1::2], size=labelsize) if ext_count == 1: pl.gca().set_xlabel('Fraction of BS neurons in STN', size=labelsize) if ext_count == 2: cax = fig.add_axes([0.895, 0.15, 0.025, 0.25]) cbar = pl.colorbar(orientation='vertical', cax=cax, cmap=cm.coolwarm) cbar.set_label('Spectral entropy of STN', position=(1.3, 0.5), fontsize=labelsize, rotation='vertical') cbar.set_ticks(cr) pl.gca().set_yticks([]) cticks = pl.getp(cbar.ax.axes, 'yticklabels') pl.setp(cticks, fontsize=labelsize) if ext_count == 0: pl.gca().set_yticks([0., 0.5, 1.0]) pl.gca().set_yticklabels([0., 0.5, 1.0], size=labelsize) pl.gca().set_ylabel('Fraction of BS neurons in GPe', size=labelsize) else: ax1.set_yticks([]) ax1.text(-0.1, 1.2, tex_lis[ext_count], size=labelsize + 5) #ax1 = fig.add_axes([0.7,0.1,0.225,0.35]) #for inh_count, inh_val in enumerate(inh_range): #spec_lis = [] #for exc_count, exc_val in enumerate(exc_range): #ad1 = get_sim_3d({'pg_rate_exc':4900., 'pg_rate_inh':1800.,'exc2_ratio':exc_val, 'inh2_ratio':inh_val}) #xx,xx,xx,peak_freq_gpe, peak_pow_gpe = ad1.psd(time_range = [ad1.pars['T_wup'],ad1.pars['T_wup']+ ad1.pars['T_sim']],pop_id = popul)
def __execute_baseline(self): #print "calibration begins..." #select the totalpower data for antenna1,2=1 (DV01, vertex antenna) # use generic pylab if type(self.antid) == list and len(self.antid) > 2: #print "Assume the antenna selection is all..." casalog.post( "Assume the antenna selection is all..." ) self.open_table(self.infile) ndat = 0 pl.ioff() # determine the size of processing data subtb = self.table.query('any(ANTENNA1==%s && ANTENNA2==%s)' % (self.antid,self.antid)) nr = subtb.nrows() #nr = len(data)*len(data[0]) #ndatcol = numpy.zeros((npol,nr),dtype=numpy.float) ndatcol = subtb.getcol(self.datacol) (l,m,n) = ndatcol.shape # m (= nchan) should be 1 since the task is specifically designed for total power data ndatcol.reshape(l,n) for np in range(len(self.selcorrtypeind)): pl.figure(np+1) pl.clf() pl.subplot(311) #pl.title(infile+' Ant:'+str(antlist.values())) pl.ylabel(self.datacol,fontsize='smaller') symbols=['b.','c.'] #print "Arranging data by scans..." casalog.post( "Arranging data by scans..." ) data = [] flag = [] ndat0 = 0 ndat = 0 if self.selnpol == 1: np = self.selpol pl.title(self.infile.rstrip('/')+' Ant:'+self.antnameused+' '+self.corrtypestr[np]) casalog.post( "select %s data..." % self.corrtypestr[np] ) for i in xrange(self.nscan): idata = [] iflag = [] #for j in xrange(nsubscan): for j in xrange(self.nsubscan[i]): # may be need to iterate on each antenna # identify 'scan' by STATE ID #selsubtb=tb.query('any(ANTENNA1==%s && ANTENNA2==%s) && SCAN_NUMBER==%s && STATE_ID==%s' % (antid,antid,scans[i],subscans[j])) selsubtb = self.table.query('any(ANTENNA1==%s && ANTENNA2==%s) && SCAN_NUMBER==%s && STATE_ID==%s' % (self.antid,self.antid,self.scans[i],self.subscans[i][j])) datcol = selsubtb.getcol(self.datacol) flgcol = selsubtb.getcol("FLAG") # only channel flag is needed to be hanled in MS selsubtb.close() if self.npol > 1 and self.selnpol == 1: #casalog.post( "select %s data..." % corrtypestr[selpol] ) rdatcol = datcol[self.selpol].real flagcell = flgcol[self.selpol] else: rdatcol = datcol[self.selcorrtypeind[np]].real flagcell = flgcol[self.selpol] (m,n) = rdatcol.shape if flagcell.shape != (m,n): raise Exception, "Data conformation error. Shape of FLAG and %s differs." % self.datacol rdatcol = rdatcol.reshape(n) flagcell = flagcell.reshape(n) #data.append(rdatcol) idata.append(rdatcol) iflag.append(flagcell) ndat0 = ndat ndat += len(rdatcol) data.append(idata) flag.append(iflag) if abs(self.plotlevel) > 0: pl.xlim(0,ndat) t1 = pl.getp(pl.gca(), 'xticklabels') t2 = pl.getp(pl.gca(), 'yticklabels') pl.setp((t1,t2), fontsize='smaller') mdat = 0 for i in xrange(self.nscan): #for j in xrange(nsubscan): for j in xrange(self.nsubscan[i]): mdat0 = mdat mdat += len(data[i][j]) masked_data = numpy.ma.masked_array(data[i][j], flag[i][j]) #pl.plot(xrange(mdat0,mdat),data[i][j],symbols[subscans[j]%2]) #pl.plot(xrange(mdat0,mdat), data[i][j], symbols[self.subscans[i][j]%2]) pl.plot(xrange(mdat0,mdat), masked_data, symbols[self.subscans[i][j]%2]) ax = pl.gca() if i == 1: leg = ax.legend(('even subscan no.', 'odd subscan no.'), numpoints=1, handletextsep=0.01) for t in leg.get_texts(): t.set_fontsize('small') pl.ion() pl.plot() #pl.draw() ### Calibration ############################################ # Do a zero-th order calibration by subtracting a baseline # # from each scan to take out atmospheric effect. # # The baseline fitting range specified by masklist must be # # given and is the same for all the scans. # ############################################################ f = sd.fitter() f.set_function(lpoly = self.blpoly) #print "Processing %s %s scans" % (corrtypestr[np], nscan) casalog.post( "Processing %s %s scans" % (self.corrtypestr[np], self.nscan) ) cdat = numpy.array([]) pl.subplot(312) pl.ioff() for i in xrange(self.nscan): casalog.post( "Processing Scan#=%s" % i ) #for j in xrange(nsubscan): for j in xrange(self.nsubscan[i]): masks = numpy.zeros(len(data[i][j]), dtype=numpy.int) if self.left_mask >= len(data[i][j]) \ or self.right_mask >= len(data[i][j]): msg = "Too large mask. All data will be used for baseline subtraction.\n The fitting may not be correct since it might confuse signal component as a background..." casalog.post(msg, "WARN") else: msg = "Subtracting baselines, set masks for fitting at row ranges: [0,%s] and [%s,%s] " % (self.left_mask-1, len(masks)-self.right_mask, len(masks)-1) casalog.post(msg, "INFO") #Use edge channels for fitting excluding flagged integrations. #masks[:self.left_mask] = True #masks[-self.right_mask:] = True masks[:self.left_mask] = (flag[i][j][:self.left_mask]==False) masks[-self.right_mask:] = (flag[i][j][-self.right_mask:]==False) x = xrange(len(data[i][j])) if self.plotlevel > 1: pl.cla() pl.ioff() pl.title('scan %s subscan %s'%(self.scans[i],self.subscans[i][j])) #pl.plot(x, data[i][j], 'b') pl.plot(x, numpy.ma.masked_array(data[i][j], flag[i][j]), 'b') f.set_data(x, data[i][j], mask=masks) f.fit() #f.plot(residual=True, components=[1], plotparms=True) fitd=f.get_fit() data[i][j] = data[i][j]-fitd if self.plotlevel > 1: pl.ion() pl.plot(xrange(len(fitd)), fitd, 'r-') pl.draw() pl.cla() pl.ioff() pl.title('scan %s subscan %s'%(self.scans[i], self.subscans[i][j])) pl.ion() #pl.plot(x, data[i][j], 'g') pl.plot(x, numpy.ma.masked_array(data[i][j], flag[i][j]), 'g') pl.draw() if interactive: check=raw_input('Hit return for Next\n') cdat = numpy.concatenate([cdat,data[i][j]]) ndatcol[np] = cdat del data subtb.close() self.close_table() self.open_table(self.infile, nomodify=False) # put the corrected data to CORRECTED_DATA column in MS # assuming the data for the vertex are stored in every other # row starting from 2nd row for the vertex antenna.... # For the alcatel startrow=0, for len(antid) >1, # it assumes all the data to be corrected. if type(self.antid) == int: startrow = self.antid rowincr = self.nant else: startrow = 0 rowincr = 1 casalog.post( "Storing the corrected data to %s column in the MS..."%self.datacol ) casalog.post( "Note that %s will be overwritten"%self.datacol ) cdatm = ndatcol.reshape(self.npol,1,len(cdat)) self.table.putcol(self.datacol, cdatm, startrow=startrow, rowincr=rowincr) self.close_table() # calibration end # # plot corrected data if abs(self.plotlevel) > 0: casalog.post( "plotting corrected data..." ) self.__plot(subplot=313, title=False, ylabel='CORRECTED_DATA')
ax.set_ylim((0.0, MaxVal)) mindate = min(pylab.date2num(datetimes[-1]), (pylab.date2num(datetimes[0])) ) maxdate = max(pylab.date2num(datetimes[-1]), (pylab.date2num(datetimes[0])) ) ax.set_xlim( (mindate, maxdate) ) #noLabels = NullLocator() #Labels = NullFormatter() ax.xaxis.set_major_locator(days) ax.xaxis.set_major_formatter(daysFmt) labels = ax.xaxis.get_ticklabels() print labels #print pylab.setp(labels) print pylab.getp(labels[0], "fontsize") ##pylab.setp(labels, ## rotation=45, ## horizontalalignment='right', ## dashlength=3, ## dashpad=0, ## fontsize=10) for l in labels: print "setting properties" l.set_rotation(45) l.set_horizontalalignment('right') l.set_dashlength(3) l.set_dashpad(0) l.set_fontsize(16)
def plotMultiplePMFs(*InferenceObjects, **kwargs): """ Plot multiple psychometric functions :Parameters: *InferenceObjects* : The Inference Objects that should be plotted. If the inference objects contain information about themselves, this information is used. *ax* : the axis object where the plot should go *xlabel* : text to be written on the y axis *ylabel* : text to be written on the x axis *ci* : boolean indicating whether credibility intervals should be drawn by default, this is False :Example: This example shows how to plot multiple psychometric functions >>> d0 = [[0, 28, 50], [2, 33, 50], [4, 38, 50], [6, 45, 50], [8, 45, 50], [10, 49, 50]] >>> d1 = [[0, 22, 50], [2, 34, 50], [4, 31, 50], [6, 42, 50], [8, 42, 50], [10, 46, 50]] >>> d2 = [[0, 26, 50], [2, 31, 50], [4, 38, 50], [6, 47, 50], [8, 49, 50], [10, 49, 50]] >>> constraints = ("","","Uniform(0,.1)") >>> B0 = BootstrapInference ( d0, priors=constraints,plotprm={"color": "r", "label": "Condition 0"} ) >>> B1 = BootstrapInference ( d1, priors=constraints, plotprm={"color": "b","label": "Condition 1"} ) >>> B2 = BootstrapInference ( d2, priors=constraints, plotprm={"color": "b","label": "Condition 2"} ) >>> plotMultiplePMFs ( B0, B1, B2 ) """ ax = kwargs.setdefault("ax", None) if ax is None: ax = p.axes() pmflines = [] pmflabels = [] pmfdata = [] for pmf in InferenceObjects: l, d = plotPMF(pmf, showaxes=False, showdesc=False, ax=ax)[:2] pmflines.append(l) pmfdata.append(d) pmflabels.append(pmf.label) if kwargs.setdefault("ci", False): plotThres(pmf, ax, color=pmf.color) ylabel_text = kwargs.setdefault("ylabel", None) if ylabel_text is None: if pmf.model["nafc"] < 2: ylabel_text = "P(Yes)" else: ylabel_text = "P(correct)" # Determine tics # p.setp(ax,frame_on=False,ylim=(-.05,1.05)) xtics = p.getp(ax, 'xticks') ytics = list(p.getp(ax, 'yticks')) # Clean up ytics for k, yt in enumerate(ytics): if yt < 0 or yt > 1: ytics.pop(k) ytics = N.array(ytics) drawaxes(ax, xtics, "%g", ytics, "%g", kwargs.setdefault("xlabel", "stimulus intensity"), ylabel_text) # Draw legend ax.legend(pmflines, pmflabels, 'lower right') return pmflines, pmfdata
def animate_interactive(data, t=None, dim_order=(0, 1, 2), fps=10.0, title=None, xlabel='x', ylabel='y', font_size=24, color_bar=0, colorbar_label=None, sloppy=True, fancy=False, range_min=None, range_max=None, extent=[-1, 1, -1, 1], shade=False, azdeg=0, altdeg=65, arrowsX=None, arrowsY=None, arrows_resX=10, arrows_resY=10, arrows_pivot='mid', arrows_width=0.002, arrows_scale=5, arrows_color='black', plot_arrows_grid=False, movie_file=None, bitrate=1800, keep_images=False, figsize=(8, 7), dpi=300, **kwimshow): """ Assemble a 2D animation from a 3D array. call signature:: animate_interactive(data, t=None, dim_order=(0, 1, 2), fps=10.0, title=None, xlabel='x', ylabel='y', font_size=24, color_bar=0, colorbar_label=None, sloppy=True, fancy=False, range_min=None, range_max=None, extent=[-1, 1, -1, 1], shade=False, azdeg=0, altdeg=65, arrowsX=None, arrowsY=None, arrows_resX=10, arrows_resY=10, arrows_pivot='mid', arrows_width=0.002, arrows_scale=5, arrows_color='black', plot_arrows_grid=False, movie_file=None, bitrate=1800, keep_images=False, figsize=(8, 7), dpi=300, **kwimshow) Assemble a 2D animation from a 3D array. *data* has to be a 3D array of shape [nt, nx, ny] and who's time index has the same dimension as *t*. The time index of *data* as well as its x and y indices can be changed via *dim_order*. Keyword arguments: *dim_order*: Ordering of the dimensions in the data array (t, x, y). *fps*: Frames per second of the animation. *title*: Title of the plot. *xlabel*: Label of the x-axis. *ylabel*: Label of the y-axis. *font_size*: Font size of the title, x and y label. The size of the x- and y-ticks is 0.5*font_size and the colorbar ticks' font size is 0.5*font_size. *color_bar*: [ 0 | 1 ] Determines how the colorbar changes: (0 - no cahnge; 1 - adapt extreme values). *colorbar_label*: Label of the color bar. *sloppy*: [ True | False ] If True the update of the plot lags one frame behind. This speeds up the plotting. *fancy*: [ True | False ] Use fancy font style. *range_min*, *range_max*: Range of the colortable. *extent*: [ None | (left, right, bottom, top) ] Limits for the axes (domain). *shade*: [ False | True ] If True plot a shaded relief instead of the usual colormap. Note that with this option cmap has to be specified like cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot be used with the color_bar = 0 option. *azdeg*, *altdeg*: Azimuth and altitude of the light source for the shading. *arrowsX*: Data containing the x-component of the arrows. *arrowsY*: Data containing the y-component of the arrows. *arrows_resXY*: Plot every arrows_resXY arrow in x and y. *arrows_pivot*: [ 'tail' | 'middle' | 'tip' ] The part of the arrow that is used as pivot point. *arrows_width*: Width of the arrows. *arrows_scale*: Scaling of the arrows. *arrows_color*: Color of the arrows. *plot_arrows_grid*: [ False | True ] If 'True' the grid where the arrows are aligned to is shown. *movie_file*: [ None | string ] The movie file where the animation should be saved to. If 'None' no movie file is written. Requires 'ffmpeg' to be installed. *bitrate*: Bitrate of the movie file. Set to higher value for higher quality. *keep_images*: [ False | True ] If 'True' the images for the movie creation are not deleted. *figsize*: Size of the figure in inches. *dpi*: Dots per inch of the frame. **kwimshow: Remaining arguments are identical to those of pylab.imshow. Refer to that help. """ try: import thread except: import _thread as thread # We need to define these variables as globals, as they are being used # by various functions. global time_step, time_slider, pause global fig, axes, image, colorbar, arrows, manager, n_times, movie_files global rgb, plot_arrows if title is None: title = '' def plot_frame(): """ Plot the current frame. """ global time_step, axes, colorbar, arrows, manager, rgb # Define the plot title. if not movie_file is None: axes.set_title(title + r'$\quad$' + r'$t={0:.4e}$'.format(t[time_step]), fontsize=font_size) # Update the image data. if not shade: image.set_data(data[time_step, :, :]) else: image.set_data(rgb[time_step, :, :, :]) # Update the colorbar. if color_bar == 0: pass if color_bar == 1: colorbar.set_clim(vmin=data[time_step, :, :].min(), vmax=data[time_step, :, :].max()) colorbar.draw_all() # Update the arrows data. if plot_arrows: arrows.set_UVC(U=arrowsX[time_step, ::arrows_resX, ::arrows_resY], V=arrowsY[time_step, ::arrows_resX, ::arrows_resY]) if not sloppy or (not movie_file is None): manager.canvas.draw() def play(thread_name): """ Play the movie. """ import time global time_step, time_slider, pause, fig, axes, n_times, movie_files pause = False while (time_step < n_times) and (not pause): # Write the image files for the movie. if not movie_file is None: plot_frame() frame_name = '{0}{1:06}.png'.format(movie_file, time_step) fig.savefig(frame_name, dpi=dpi) movie_files.append(frame_name) else: time_start = time.clock() time_slider.set_val(t[time_step]) # Wait for the next frame (fps). while (time.clock() - time_start < 1.0 / fps): pass time_step += 1 time_step -= 1 def play_thread(event): """ Call the play function as a separate thread (for GUI). """ global pause if pause: try: thread.start_new_thread(play, ("play_thread", )) except: print("Error: unable to start play thread.") def pausing(event): global pause pause = True def reverse(event): global time_step, time_slider time_step -= 1 if time_step < 0: time_step = 0 # Plot the frame and update the time slider. time_slider.set_val(t[time_step]) def forward(event): global time_step, time_slider time_step += 1 if time_step > len(t) - 1: time_step = len(t) - 1 # Plot the frame and update the time slider. time_slider.set_val(t[time_step]) import numpy as np import pylab as plt pause = True plot_arrows = False # Check if the data has the right dimensions. if (data.ndim != 3 and data.ndim != 4): print("Error: data dimensions are invalid: {0} instead of 3.".format( data.ndim)) return -1 # Transpose the data according to dim_order. unordered_data = data data = np.transpose(unordered_data, dim_order) del (unordered_data) # Check if arrows should be plotted. if not (arrowsX is None) and not (arrowsY is None): if (isinstance(arrowsX, np.ndarray) and isinstance(arrowsY, np.ndarray)): if arrowsX.ndim == 3: # Transpose the data according to dim_order. unordered_data = arrowsX arrowsX = np.transpose(unordered_data, dim_order) del (unordered_data) if arrowsY.ndim == 3: # Transpose the data according to dim_order. unordered_data = arrowsY arrowsY = np.transpose(unordered_data, dim_order) unordered_data = [] # Check if the dimensions of the arrow arrays match each other. if arrowsX.shape != arrowsY.shape: print( "Error: dimensions of arrowX do not match with dimensions of arrowY." ) return -1 else: plot_arrows = True else: print("Warning: arrowsX and/or arrowsY are of invalid type.") # Check if time array has the right length. n_times = len(t) if n_times != data.shape[0]: print( "Error: length of time array does not match length of data array.") return -1 if plot_arrows: if (n_times != arrowsX.shape[0]) or (n_times != arrowsY.shape[0]): print( "error: length of time array does not match length of arrows array." ) return -1 # Check if fps is positive. if fps < 0: print("Error: fps is not positive, fps = {0}.".format(fps)) return -1 # Determine the size of the data array. nX = data.shape[1] nY = data.shape[2] # Determine the minimum and maximum values of the data set. if not range_min: range_min = np.min(data) if not range_max: range_max = np.max(data) # Setup the plot. if fancy: plt.rc('text', usetex=True) plt.rc('font', family='arial') else: plt.rc('text', usetex=False) plt.rc('font', family='sans') if not movie_file is None: fig = plt.figure(figsize=figsize) axes = plt.axes([0.15, 0.1, .70, .85]) else: fig = plt.figure(figsize=figsize) axes = plt.axes([0.1, 0.3, .80, .65]) # Set up canvas of the plot. axes.set_title(title, fontsize=font_size) axes.set_xlabel(xlabel, fontsize=font_size) axes.set_ylabel(ylabel, fontsize=font_size) plt.xticks(fontsize=0.5 * font_size) plt.yticks(fontsize=0.5 * font_size) if shade: plane = np.zeros([nX, nY, 3]) else: plane = np.zeros([nX, nY]) # Apply shading. if shade: from matplotlib.colors import LightSource ls = LightSource(azdeg=azdeg, altdeg=altdeg) rgb = [] # Shading can be only used with color_bar=1 or color_bar=2 at the moment. if color_bar == 0: color_bar = 1 # Check if colormap is set, if not set it to 'copper'. if 'cmap' not in kwimshow.keys(): kwimshow['cmap'] = plt.cm.copper for i in range(data.shape[0]): tmp = ls.shade(data[i, :, :], kwimshow['cmap']) rgb.append(tmp.tolist()) rgb = np.array(rgb) del (tmp) # Calibrate the displayed colors for the data range. image = axes.imshow(plane, vmin=range_min, vmax=range_max, origin='lower', extent=extent, **kwimshow) colorbar = fig.colorbar(image) colorbar.set_label(colorbar_label, fontsize=font_size, labelpad=10) # Change the font size of the colorbar's ytickslabels. cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels') plt.setp(cbytick_obj, fontsize=0.5 * font_size) # Plot the arrows. if plot_arrows: # Prepare the mesh grid where the arrows will be drawn. arrow_grid = np.meshgrid( np.arange( extent[0], extent[1], float(extent[1] - extent[0]) * arrows_resX / (data.shape[2] - 1)), np.arange( extent[2], extent[3], float(extent[3] - extent[2]) * arrows_resY / (data.shape[1] - 1))) arrows = axes.quiver(arrow_grid[0], arrow_grid[1], arrowsX[0, ::arrows_resX, ::arrows_resY], arrowsY[0, ::arrows_resX, ::arrows_resY], units='width', pivot=arrows_pivot, width=arrows_width, scale=arrows_scale, color=arrows_color) # Plot the grid for the arrows. if plot_arrows_grid: axes.plot(arrow_grid[0], arrow_grid[1], 'k.') # For real-time image display. if (not sloppy) or (not movie_file is None): manager = plt.get_current_fig_manager() manager.show() time_step = 0 if not movie_file is None: import os movie_files = [] # Start the animation. play('no_thread') # Write the movie file. ffmpeg_command = "ffmpeg -r {0} -i {1}%6d.png -vcodec mpeg4 -b:v {2} -q:v 0 {3}.avi".format( fps, movie_file, bitrate, movie_file) os.system(ffmpeg_command) # Clean up the image files. if not keep_images: print("Cleaning up files.") for fname in movie_files: os.remove(fname) else: # Set up the gui. plt.ion() plt.subplots_adjust(bottom=0.2) # axes_play = plt.axes([0.1, 0.05, 0.15, 0.05]) # button_play = plt.Button(axes_play, 'play', color='lightgoldenrodyellow', # hovercolor='0.975') # button_play.on_clicked(play_thread) # axes_pause = plt.axes([0.3, 0.05, 0.15, 0.05]) # button_pause = plt.Button(axes_pause, 'pause', color='lightgoldenrodyellow', # hovercolor='0.975') # button_pause.on_clicked(pausing) # axes_reverse = plt.axes([0.5, 0.05, 0.15, 0.05]) axes_reverse = plt.axes([0.1, 0.05, 0.3, 0.05]) button_reverse = plt.Button(axes_reverse, 'reverse', color='lightgoldenrodyellow', hovercolor='0.975') button_reverse.on_clicked(reverse) # axes_forward = plt.axes([0.7, 0.05, 0.15, 0.05]) axes_forward = plt.axes([0.5, 0.05, 0.3, 0.05]) button_forward = plt.Button(axes_forward, 'forward', color='lightgoldenrodyellow', hovercolor='0.975') button_forward.on_clicked(forward) # Create the time slider. time_slider_axes = plt.axes([0.2, 0.12, 0.6, 0.03], facecolor='lightgoldenrodyellow') time_slider = plt.Slider(time_slider_axes, 'time', t[0], t[-1], valinit=t[0]) def update(val): global time_step # Find the closest time step to the slider time value. for i in range(len(t)): if t[i] < time_slider.val: time_step = i if (time_step != len(t) - 1): if (t[time_step + 1] - time_slider.val) < (time_slider.val - t[time_step]): time_step += 1 plot_frame() time_slider.on_changed(update) plt.show() print("done") # return button_play, button_pause, button_reverse, button_forward return button_reverse, button_forward
def animate_interactive(data, t = [], dimOrder = (0,1,2), fps = 10.0, title = '', xlabel = 'x', ylabel = 'y', fontsize = 24, cBar = 0, sloppy = True, rangeMin = [], rangeMax = [], extent = [-1,1,-1,1], shade = False, azdeg = 0, altdeg = 65, arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10, arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5, arrowsColor = 'black', plotArrowsGrid = False, movieFile = '', bitrate = 1800, keepImages = False, figsize = (8, 7), dpi = None, **kwimshow): """ Assemble a 2D animation from a 3D array. call signature:: animate_interactive(data, t = [], dimOrder = (0,1,2), fps = 10.0, title = '', xlabel = 'x', ylabel = 'y', fontsize = 24, cBar = 0, sloppy = True, rangeMin = [], rangeMax = [], extent = [-1,1,-1,1], shade = False, azdeg = 0, altdeg = 65, arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10, arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5, arrowsColor = 'black', plotArrowsGrid = False, movieFile = '', bitrate = 1800, keepImages = False, figsize = (8, 7), dpi = None, **kwimshow) Assemble a 2D animation from a 3D array. *data* has to be a 3D array who's time index has the same dimension as *t*. The time index of *data* as well as its x and y indices can be changed via *dimOrder*. Keyword arguments: *dimOrder*: [ (i,j,k) ] Ordering of the dimensions in the data array (t,x,y). *fps*: Frames per second of the animation. *title*: Title of the plot. *xlabel*: Label of the x-axis. *ylabel*: Label of the y-axis. *fontsize*: Font size of the title, x and y label. The size of the x- and y-ticks is 0.7*fontsize and the colorbar ticks's font size is 0.5*fontsize. *cBar*: [ 0 | 1 | 2 ] Determines how the colorbar changes: (0 - no cahnge; 1 - keep extreme values constant; 2 - change extreme values). *sloppy*: [ True | False ] If True the update of the plot lags one frame behind. This speeds up the plotting. *rangeMin*, *rangeMax*: Range of the colortable. *extent*: [ None | scalars (left, right, bottom, top) ] Data limits for the axes. The default assigns zero-based row, column indices to the *x*, *y* centers of the pixels. *shade*: [ False | True ] If True plot a shaded relief plot instead of the usual colormap. Note that with this option cmap has to be specified like cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot be used with the cBar = 0 option. *azdeg*, *altdeg*: Azimuth and altitude of the light source for the shading. *arrowsX*: Data containing the x-component of the arrows. *arrowsy*: Data containing the y-component of the arrows. *arrowsRes*: Plot every arrowRes arrow. *arrowsPivot*: [ 'tail' | 'middle' | 'tip' ] The part of the arrow that is at the grid point; the arrow rotates about this point. *arrowsWidth*: Width of the arrows. *arrowsScale*: Scaling of the arrows. *arrowsColor*: Color of the arrows. *plotArrowsGrid*: [ False | True ] If 'True' the grid where the arrows are aligned to is shown. *movieFile*: [ None | string ] The movie file where the animation should be saved to. If 'None' no movie file is written. Requires 'mencoder' to be installed. *bitrate*: Bitrate of the movie file. Set to higher value for higher quality. *keepImages*: [ False | True ] If 'True' the images for the movie creation are not deleted. *figsize*: Size of the figure in inches. *dpi*: Dots per inch of the frame. **kwimshow: Remaining arguments are identical to those of pylab.imshow. Refer to that help. """ global tStep, sliderTime, pause # plot the current frame def plotFrame(): global tStep, sliderTime if movieFile: ax.set_title(title+r'$\quad$'+r'$t={0}$'.format(t[tStep]), fontsize = fontsize) if shade == False: image.set_data(data[tStep,:,:]) else: image.set_data(rgb[tStep,:,:,:]) if (cBar == 0): pass if (cBar == 1): colorbar.set_clim(vmin=data[tStep,:,:].min(), vmax=data[tStep,:,:].max()) if (cBar == 2): colorbar.set_clim(vmin=data[tStep,:,:].min(), vmax=data[tStep,:,:].max()) colorbar.update_bruteforce(data[tStep,:,:]) if plotArrows: arrows.set_UVC(U = arrowsX[tStep,::arrowsRes,::arrowsRes], V = arrowsY[tStep,::arrowsRes,::arrowsRes]) if (sloppy == False) or (movieFile): manager.canvas.draw() # play the movie def play(threadName): global tStep, sliderTime, pause pause = False while (tStep < nT) & (pause == False): # write the image files for the movie if movieFile: plotFrame() frameName = movieFile + '%06d.png'%tStep fig.savefig(frameName, dpi = dpi) movieFiles.append(frameName) else: start = time.clock() # time slider sliderTime.set_val(t[tStep]) # wait for the next frame (fps) while (time.clock() - start < 1.0/fps): pass # do nothing tStep += 1 tStep -= 1 # call the play function as a separate thread (for GUI) def play_thread(event): global pause if pause == True: try: thread.start_new_thread(play, ("playThread", )) except: print "Error: unable to start play thread" def pausing(event): global pause pause = True def reverse(event): global tStep, sliderTime tStep -= 1 if tStep < 0: tStep = 0 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) def forward(event): global tStep, sliderTime tStep += 1 if tStep > len(t)-1: tStep = len(t)-1 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) pause = True plotArrows = False # check if the data has the right dimensions if (len(data.shape) != 3 and len(data.shape) != 4): print 'error: data dimensions are invalid: {0} instead of 3'.format(len(data.shape)) return -1 # transpose the data according to dimOrder unOrdered = data data = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if arrows should be plotted if len(arrowsX.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsX arrowsX = np.transpose(unOrdered, dimOrder) unOrdered = [] if len(arrowsY.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsY arrowsY = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if the dimensions of the arrow arrays match each other if ((len(arrowsX[:,0,0]) != len(arrowsY[:,0,0])) or (len(arrowsX[0,:,0]) != len(arrowsY[0,:,0])) or (len(arrowsX[0,0,:]) != len(arrowsY[0,0,:]))): print 'error: dimensions of arrowX do not match with dimensions of arrowY' return -1 else: plotArrows = True # check if time array has the right length nT = len(t) if (nT != len(data[:,0,0])): print 'error: length of time array doesn\'t match length of data array' return -1 if plotArrows: if (nT != len(arrowX[:,0,0]) or nT != len(arrowX[:,0,0])): print 'error: length of time array doesn\'t match length of arrows array' return -1 # check if fps is positive if (fps < 0.0): print 'error: fps is not positive, fps = {0}'.format(fps) return -1 # determine the size of the array nX = len(data[0,:,0]) nY = len(data[0,0,:]) # determine the minimum and maximum values of the data set if not(rangeMin): rangeMin = np.min(data) if not(rangeMax): rangeMax = np.max(data) # setup the plot if movieFile: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.15) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize = figsize) ax = plt.axes([0.1, 0.1, .90, .85]) else: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.05) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize = figsize) ax = plt.axes([0.1, 0.25, .85, .70]) ax.set_title(title, fontsize = fontsize) ax.set_xlabel(xlabel, fontsize = fontsize) ax.set_ylabel(ylabel, fontsize = fontsize) plt.xticks(fontsize = 0.7*fontsize) plt.yticks(fontsize = 0.7*fontsize) if shade: plane = np.zeros((nX,nY,3)) else: plane = np.zeros((nX,nY)) # apply shading if True if shade: ls = LightSource(azdeg = azdeg, altdeg = altdeg) rgb = [] # shading can be only used with cBar = 1 or cBar = 2 at the moment if cBar == 0: cBar = 1 # check if colormap is set, if not set it to 'copper' if kwimshow.has_key('cmap') == False: kwimshow['cmap'] = plt.cm.copper for i in range(len(data[:,0,0])): tmp = ls.shade(data[i,:,:], kwimshow['cmap']) rgb.append(tmp.tolist()) rgb = np.array(rgb) tmp = [] # calibrate the displayed colors for the data range image = ax.imshow(plane, vmin=rangeMin, vmax=rangeMax, origin='lower', extent = extent, **kwimshow) colorbar = fig.colorbar(image) # change the font size of the colorbar's ytickslabels cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels') plt.setp(cbytick_obj, fontsize = 0.5*fontsize) # plot the arrows # TODO: add some more options if plotArrows: # prepare the mash grid where the arrows will be drawn arrowGridX, arrowGridY = np.meshgrid(np.arange(extent[0], extent[1], float(extent[1]-extent[0])*arrowsRes/len(data[0,:,0])), np.arange(extent[2], extent[3], float(extent[3]-extent[2])*arrowsRes/len(data[0,0,:]))) arrows = ax.quiver(arrowGridX, arrowGridY, arrowsX[0,::arrowsRes,::arrowsRes], arrowsY[0,::arrowsRes,::arrowsRes], units = 'width', pivot = arrowsPivot, width = arrowsWidth, scale = arrowsScale, color = arrowsColor) # plot the grid for the arrows if plotArrowsGrid == True: ax.plot(arrowGridX, arrowGridY, 'k.') # for real-time image display if (sloppy == False) or (movieFile): manager = plt.get_current_fig_manager() manager.show() tStep = 0 if movieFile: movieFiles = [] # start the animation play('noThread') # write the movie file mencodeCommand = "mencoder 'mf://"+movieFile+"*.png' -mf type=png:fps="+np.str(fps)+" -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate="+np.str(bitrate)+" -ffourcc MP4S -oac copy -o "+movieFile+".mpg" os.system(mencodeCommand) # clean up the image files if (keepImages == False): print 'cleaning up files' for fname in movieFiles: os.remove(fname) else: # set up the gui plt.ion() axPlay = plt.axes([0.1, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPlay = plt.Button(axPlay, 'play', color='lightgoldenrodyellow', hovercolor='0.975') buttonPlay.on_clicked(play_thread) axPause = plt.axes([0.3, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPause = plt.Button(axPause, 'pause', color='lightgoldenrodyellow', hovercolor='0.975') buttonPause.on_clicked(pausing) axReverse = plt.axes([0.5, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonReverse = plt.Button(axReverse, 'reverse', color='lightgoldenrodyellow', hovercolor='0.975') buttonReverse.on_clicked(reverse) axForward = plt.axes([0.7, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonForward = plt.Button(axForward, 'forward', color='lightgoldenrodyellow', hovercolor='0.975') buttonForward.on_clicked(forward) # create the time slider fig.subplots_adjust(bottom=0.2) sliderTimeAxes = plt.axes([0.2, 0.12, 0.6, 0.03], axisbg='lightgoldenrodyellow') sliderTime = plt.Slider(sliderTimeAxes, 'time', t[0], t[-1], valinit = 0.0) def update(val): global tStep # find the closest time step to the slider time value for i in range(len(t)): if t[i] < sliderTime.val: tStep = i if (tStep != len(t)-1): if (t[tStep+1] - sliderTime.val) < (sliderTime.val - t[tStep]): tStep += 1 plotFrame() sliderTime.on_changed(update) plt.show() print 'done'
def plotConfusion(confusion, map, grid_spacing, title, file_name, inset=None, fudge=16): pylab.figure() axmain = pylab.axes() gs_x, gs_y = grid_spacing confusion_cmap_dict = { 'red':( (0.0, 0.5, 0.5), (0.25, 0.5, 1.0), (0.5, 1.0, 0.0), (0.75, 0.0, 1.0), (1.0, 1.0, 1.0), ), 'green':( (0.0, 0.5, 0.5), (0.25, 0.5, 0.0), (0.5, 0.0, 1.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0), ), 'blue':( (0.0, 0.5, 0.5), (0.25, 0.5, 1.0), (0.5, 1.0, 0.0), (0.75, 0.0, 1.0), (1.0, 1.0, 1.0), ), } confusion_cmap = LinearSegmentedColormap('confusion', confusion_cmap_dict, 256) nx, ny = confusion.shape xs, ys = np.meshgrid( gs_x * np.arange(nx), gs_y * np.arange(ny) ) pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=0, vmax=3) tick_locs = [ 0.375 + 0.75 * l for l in range(4) ] tick_labels = [ "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ] bar = pylab.colorbar() bar.locator = FixedLocator(tick_locs) bar.formatter = FixedFormatter(tick_labels) pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large') bar.update_ticks() drawPolitical(map, scale_len=25) if inset: lb_y, lb_x = [ b.start for b in inset ] ub_y, ub_x = [ b.stop + fudge for b in inset ] inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x)) axins = zoomed_inset_axes(pylab.gca(), 2, loc=4) pylab.sca(axins) pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=0, vmax=3) drawPolitical(map) pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x]) pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
pylab.figure(1,figsize=(22,2)) marker_gene_coverages = parse_midas_data.parse_marker_gene_coverage_distribution(species_name) max_coverages = [] median_coverages = [] marker_genes = sorted(marker_gene_coverages[marker_gene_coverages.keys()[0]].keys()) for sample in desired_samples: current_loc = 0 pooled_coverages = [] line, = pylab.plot([-1],[1],'-') color = pylab.getp(line,'color') print sample for gene_idx in xrange(0,len(marker_genes)): gene_name = marker_genes[gene_idx] current_loc += 1 pylab.plot([current_loc,current_loc],[1e-09,1e09],'k-') current_loc += 1 if gene_idx%2==0: pylab.text(current_loc+10, 900, gene_name, fontsize=6) else: pylab.text(current_loc+10, 800, gene_name, fontsize=6) locs,depths = marker_gene_coverages[sample][gene_name]
def animate_interactive(data, t=[], dimOrder=(0, 1, 2), fps=10.0, title='', xlabel='x', ylabel='y', fontsize=24, cBar=0, sloppy=True, rangeMin=[], rangeMax=[], extent=[-1, 1, -1, 1], shade=False, azdeg=0, altdeg=65, arrowsX=np.array(0), arrowsY=np.array(0), arrowsRes=10, arrowsPivot='mid', arrowsWidth=0.002, arrowsScale=5, arrowsColor='black', plotArrowsGrid=False, movieFile='', bitrate=1800, keepImages=False, figsize=(8, 7), dpi=None, **kwimshow): """ Assemble a 2D animation from a 3D array. call signature:: animate_interactive(data, t = [], dimOrder = (0,1,2), fps = 10.0, title = '', xlabel = 'x', ylabel = 'y', fontsize = 24, cBar = 0, sloppy = True, rangeMin = [], rangeMax = [], extent = [-1,1,-1,1], shade = False, azdeg = 0, altdeg = 65, arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10, arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5, arrowsColor = 'black', plotArrowsGrid = False, movieFile = '', bitrate = 1800, keepImages = False, figsize = (8, 7), dpi = None, **kwimshow) Assemble a 2D animation from a 3D array. *data* has to be a 3D array who's time index has the same dimension as *t*. The time index of *data* as well as its x and y indices can be changed via *dimOrder*. Keyword arguments: *dimOrder*: [ (i,j,k) ] Ordering of the dimensions in the data array (t,x,y). *fps*: Frames per second of the animation. *title*: Title of the plot. *xlabel*: Label of the x-axis. *ylabel*: Label of the y-axis. *fontsize*: Font size of the title, x and y label. The size of the x- and y-ticks is 0.7*fontsize and the colorbar ticks's font size is 0.5*fontsize. *cBar*: [ 0 | 1 | 2 ] Determines how the colorbar changes: (0 - no cahnge; 1 - keep extreme values constant; 2 - change extreme values). *sloppy*: [ True | False ] If True the update of the plot lags one frame behind. This speeds up the plotting. *rangeMin*, *rangeMax*: Range of the colortable. *extent*: [ None | scalars (left, right, bottom, top) ] Data limits for the axes. The default assigns zero-based row, column indices to the *x*, *y* centers of the pixels. *shade*: [ False | True ] If True plot a shaded relief plot instead of the usual colormap. Note that with this option cmap has to be specified like cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot be used with the cBar = 0 option. *azdeg*, *altdeg*: Azimuth and altitude of the light source for the shading. *arrowsX*: Data containing the x-component of the arrows. *arrowsy*: Data containing the y-component of the arrows. *arrowsRes*: Plot every arrowRes arrow. *arrowsPivot*: [ 'tail' | 'middle' | 'tip' ] The part of the arrow that is at the grid point; the arrow rotates about this point. *arrowsWidth*: Width of the arrows. *arrowsScale*: Scaling of the arrows. *arrowsColor*: Color of the arrows. *plotArrowsGrid*: [ False | True ] If 'True' the grid where the arrows are aligned to is shown. *movieFile*: [ None | string ] The movie file where the animation should be saved to. If 'None' no movie file is written. Requires 'mencoder' to be installed. *bitrate*: Bitrate of the movie file. Set to higher value for higher quality. *keepImages*: [ False | True ] If 'True' the images for the movie creation are not deleted. *figsize*: Size of the figure in inches. *dpi*: Dots per inch of the frame. **kwimshow: Remaining arguments are identical to those of pylab.imshow. Refer to that help. """ global tStep, sliderTime, pause # plot the current frame def plotFrame(): global tStep, sliderTime if movieFile: ax.set_title(title + r'$\quad$' + r'$t={0}$'.format(t[tStep]), fontsize=fontsize) if shade == False: image.set_data(data[tStep, :, :]) else: image.set_data(rgb[tStep, :, :, :]) if (cBar == 0): pass if (cBar == 1): colorbar.set_clim(vmin=data[tStep, :, :].min(), vmax=data[tStep, :, :].max()) if (cBar == 2): colorbar.set_clim(vmin=data[tStep, :, :].min(), vmax=data[tStep, :, :].max()) colorbar.update_bruteforce(data[tStep, :, :]) if plotArrows: arrows.set_UVC(U=arrowsX[tStep, ::arrowsRes, ::arrowsRes], V=arrowsY[tStep, ::arrowsRes, ::arrowsRes]) if (sloppy == False) or (movieFile): manager.canvas.draw() # play the movie def play(threadName): global tStep, sliderTime, pause pause = False while (tStep < nT) & (pause == False): # write the image files for the movie if movieFile: plotFrame() frameName = movieFile + '%06d.png' % tStep fig.savefig(frameName, dpi=dpi) movieFiles.append(frameName) else: start = time.clock() # time slider sliderTime.set_val(t[tStep]) # wait for the next frame (fps) while (time.clock() - start < 1.0 / fps): pass # do nothing tStep += 1 tStep -= 1 # call the play function as a separate thread (for GUI) def play_thread(event): global pause if pause == True: try: thread.start_new_thread(play, ("playThread", )) except: print "Error: unable to start play thread" def pausing(event): global pause pause = True def reverse(event): global tStep, sliderTime tStep -= 1 if tStep < 0: tStep = 0 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) def forward(event): global tStep, sliderTime tStep += 1 if tStep > len(t) - 1: tStep = len(t) - 1 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) pause = True plotArrows = False # check if the data has the right dimensions if (len(data.shape) != 3 and len(data.shape) != 4): print 'error: data dimensions are invalid: {0} instead of 3'.format( len(data.shape)) return -1 # transpose the data according to dimOrder unOrdered = data data = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if arrows should be plotted if len(arrowsX.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsX arrowsX = np.transpose(unOrdered, dimOrder) unOrdered = [] if len(arrowsY.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsY arrowsY = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if the dimensions of the arrow arrays match each other if ((len(arrowsX[:, 0, 0]) != len(arrowsY[:, 0, 0])) or (len(arrowsX[0, :, 0]) != len(arrowsY[0, :, 0])) or (len(arrowsX[0, 0, :]) != len(arrowsY[0, 0, :]))): print 'error: dimensions of arrowX do not match with dimensions of arrowY' return -1 else: plotArrows = True # check if time array has the right length nT = len(t) if (nT != len(data[:, 0, 0])): print 'error: length of time array doesn\'t match length of data array' return -1 if plotArrows: if (nT != len(arrowX[:, 0, 0]) or nT != len(arrowX[:, 0, 0])): print 'error: length of time array doesn\'t match length of arrows array' return -1 # check if fps is positive if (fps < 0.0): print 'error: fps is not positive, fps = {0}'.format(fps) return -1 # determine the size of the array nX = len(data[0, :, 0]) nY = len(data[0, 0, :]) # determine the minimum and maximum values of the data set if not (rangeMin): rangeMin = np.min(data) if not (rangeMax): rangeMax = np.max(data) # setup the plot if movieFile: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.15) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize=figsize) ax = plt.axes([0.1, 0.1, .90, .85]) else: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.05) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize=figsize) ax = plt.axes([0.1, 0.25, .85, .70]) ax.set_title(title, fontsize=fontsize) ax.set_xlabel(xlabel, fontsize=fontsize) ax.set_ylabel(ylabel, fontsize=fontsize) plt.xticks(fontsize=0.7 * fontsize) plt.yticks(fontsize=0.7 * fontsize) if shade: plane = np.zeros((nX, nY, 3)) else: plane = np.zeros((nX, nY)) # apply shading if True if shade: ls = LightSource(azdeg=azdeg, altdeg=altdeg) rgb = [] # shading can be only used with cBar = 1 or cBar = 2 at the moment if cBar == 0: cBar = 1 # check if colormap is set, if not set it to 'copper' if kwimshow.has_key('cmap') == False: kwimshow['cmap'] = plt.cm.copper for i in range(len(data[:, 0, 0])): tmp = ls.shade(data[i, :, :], kwimshow['cmap']) rgb.append(tmp.tolist()) rgb = np.array(rgb) tmp = [] # calibrate the displayed colors for the data range image = ax.imshow(plane, vmin=rangeMin, vmax=rangeMax, origin='lower', extent=extent, **kwimshow) colorbar = fig.colorbar(image) # change the font size of the colorbar's ytickslabels cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels') plt.setp(cbytick_obj, fontsize=0.5 * fontsize) # plot the arrows # TODO: add some more options if plotArrows: # prepare the mash grid where the arrows will be drawn arrowGridX, arrowGridY = np.meshgrid( np.arange( extent[0], extent[1], float(extent[1] - extent[0]) * arrowsRes / len(data[0, :, 0])), np.arange( extent[2], extent[3], float(extent[3] - extent[2]) * arrowsRes / len(data[0, 0, :]))) arrows = ax.quiver(arrowGridX, arrowGridY, arrowsX[0, ::arrowsRes, ::arrowsRes], arrowsY[0, ::arrowsRes, ::arrowsRes], units='width', pivot=arrowsPivot, width=arrowsWidth, scale=arrowsScale, color=arrowsColor) # plot the grid for the arrows if plotArrowsGrid == True: ax.plot(arrowGridX, arrowGridY, 'k.') # for real-time image display if (sloppy == False) or (movieFile): manager = plt.get_current_fig_manager() manager.show() tStep = 0 if movieFile: movieFiles = [] # start the animation play('noThread') # write the movie file mencodeCommand = "mencoder 'mf://" + movieFile + "*.png' -mf type=png:fps=" + np.str( fps) + " -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate=" + np.str( bitrate) + " -ffourcc MP4S -oac copy -o " + movieFile + ".mpg" os.system(mencodeCommand) # clean up the image files if (keepImages == False): print 'cleaning up files' for fname in movieFiles: os.remove(fname) else: # set up the gui plt.ion() axPlay = plt.axes([0.1, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPlay = plt.Button(axPlay, 'play', color='lightgoldenrodyellow', hovercolor='0.975') buttonPlay.on_clicked(play_thread) axPause = plt.axes([0.3, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPause = plt.Button(axPause, 'pause', color='lightgoldenrodyellow', hovercolor='0.975') buttonPause.on_clicked(pausing) axReverse = plt.axes([0.5, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonReverse = plt.Button(axReverse, 'reverse', color='lightgoldenrodyellow', hovercolor='0.975') buttonReverse.on_clicked(reverse) axForward = plt.axes([0.7, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonForward = plt.Button(axForward, 'forward', color='lightgoldenrodyellow', hovercolor='0.975') buttonForward.on_clicked(forward) # create the time slider fig.subplots_adjust(bottom=0.2) sliderTimeAxes = plt.axes([0.2, 0.12, 0.6, 0.03], axisbg='lightgoldenrodyellow') sliderTime = plt.Slider(sliderTimeAxes, 'time', t[0], t[-1], valinit=0.0) def update(val): global tStep # find the closest time step to the slider time value for i in range(len(t)): if t[i] < sliderTime.val: tStep = i if (tStep != len(t) - 1): if (t[tStep + 1] - sliderTime.val) < (sliderTime.val - t[tStep]): tStep += 1 plotFrame() sliderTime.on_changed(update) plt.show() print 'done'
ncfile = NC(tsfile, "r") except: print "ERROR: can't open file %s for reading ..." % tsfile sys.exit(2) print " reading 'time' variable ..." t = ncfile.variables["time"][:] / secpera n = 3 style = ['b-', 'g-', 'r-'] labels = ['ocean_loss', 'ice_free_land_loss', 'negative_thickness_gain'] for k in range(n): varname = 'hydro_' + labels[k] print " reading '%s' variable ..." % varname var = ncfile.variables[varname][:] plt.semilogy(t, var / scale, style[k], linewidth=2.5) plt.hold(True) ncfile.close() plt.hold(False) yy = plt.getp(plt.gca(), 'ylim') plt.setp(plt.gca(), 'ylim', (yaxismin, yy[1])) plt.legend(labels, loc=legloc) plt.xlabel("t (years)", size=16) plt.ylabel("flux (%s kg/s)" % scalestr, size=16) plt.grid(True) print "saving image to file '%s' ..." % outimage # plt.show() plt.savefig(outimage, bbox_inches='tight')
def plot_average_oct(self,keys=None,independent=True,string=""): if independent: fig = pylab.figure() average_curves={} sem_curves={} curves={} if keys == None: keys = self.data_dict.keys() for k in keys: xindex, yindex = k curve = self.data_dict[k]["OCT"]["ORTC"]["data"] x_values = sorted(curve.keys()) m = numpy.max([curve[l].view()[0][xindex, yindex] for l in x_values]) for curve_label in self.data_dict[k]["OCT"].keys(): if curve_label != 'Contrastsurround = 0%': orientation = self.data_dict[(xindex,yindex)]["OCT"]["ORTC"]["info"]["pref_or"] curve = self.data_dict[k]["OCT"][curve_label]["data"] x_values = sorted(curve.keys()) y_values = [curve[l].view()[0][xindex, yindex] for l in x_values] x_values=numpy.array(x_values)-orientation for j in xrange(0,len(x_values)): if x_values[j] > numpy.pi/2.0: x_values[j] -= numpy.pi if x_values[j] < -numpy.pi/2.0: x_values[j] += numpy.pi for j in xrange(0,len(x_values)): if x_values[j] > numpy.pi/2.0: x_values[j] -= numpy.pi if x_values[j] < -numpy.pi/2.0: x_values[j] += numpy.pi inds = numpy.argsort(x_values) y_values = numpy.take(y_values, inds) x_values = numpy.take(x_values, inds) #x_values = sorted(x_values) if (x_values[0]+numpy.pi/2.0) < 0.0001: y_values = numpy.append(y_values,[y_values[0]]) x_values = numpy.append(x_values,[numpy.pi/2]) else: y_values = numpy.append([y_values[-1]],y_values) x_values = numpy.append([-numpy.pi/2],x_values) # normalize curve y_values = y_values / m if curves.has_key(curve_label): curves[curve_label].append(numpy.array(y_values)) else: curves[curve_label]=[numpy.array(y_values)] for curve_label in curves: average_curves[curve_label]=numpy.mean(numpy.array(curves[curve_label]),axis=0) sem_curves[curve_label]=scipy.stats.sem(numpy.array(curves[curve_label]),axis=0) colors=['red','blue','green','purple','orange','black','yellow'] i=0 for curve_label in average_curves.keys(): pylab.plot(x_values, average_curves[curve_label]*100, lw=3, color=colors[i],label=curve_label) ax = pylab.gca() ax.errorbar(x_values, average_curves[curve_label]*100, lw=1, ecolor=colors[i], yerr=sem_curves[curve_label]*100, fmt=None) ax.set_xlim(-numpy.pi/2-0.2,numpy.pi/2.0+0.2) ax.set_xticks([-numpy.pi/2,0,numpy.pi/2.0]) ax.set_yticks([0,50,100]) ax.set_yticklabels(['0%','50%','100%']) ax.set_ylim(0,110) i=i+1 #pylab.legend(loc='lower left') disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels([r'-$\frac{\pi}{2}$',r'0',r'$\frac{\pi}{2}$'], fontProperties) pylab.gca().set_yticklabels(pylab.gca().get_yticks(), fontProperties) if independent: release_fig("AverageOCTC" + string)
'axes.labelsize': 11, 'text.fontsize': 11, 'legend.fontsize': 12, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'text.usetex': True, 'figure.figsize': [5,4]} py.rcParams.update(params) import numpy as np import sys files=['1.txt','2.txt'] for f in files: data = py.loadtxt(f) x,y = data.T p, = py.plot(x[1:], y[1:], 'o-', lw=2, clip_on=False, zorder=10) c = py.getp(p,'color') py.plot(x[1], y[1], 'D', clip_on=False, zorder=10, color=c) py.plot(x[0], y[0], 's', clip_on=False, zorder=10, color=c) bbox = dict(boxstyle="round", fc="0.9") arrow = dict(arrowstyle="->") py.annotate(r'$$x=0, z=0.5$$', xy=(.029, .986), xytext=(.02, .95), bbox=bbox, arrowprops=arrow) py.annotate(r'$$x=0, z=0.1696$$', xy=(.032, .885), xytext=(.03, .92), bbox=bbox, arrowprops=arrow) py.xlabel(r'$\mathrm{Kn}$', labelpad=-1) py.ylabel(r'$T$', y=.8, labelpad=-3, rotation=0) py.xlim(0,.05) py.tight_layout() py.savefig(sys.argv[1])
def correlations_figure(self,raster_plots): self.fig = pylab.figure(facecolor='w',figsize=(15, 18),dpi=800) gs = gridspec.GridSpec(3,2) gs.update(left=0.07, right=0.95, top=0.95, bottom=0.05,wspace=0.2,hspace=0.2) ax = pylab.subplot(gs[0,0]) m,b = numpy.polyfit(raster_plots["or_suppression"][1],raster_plots["or_suppression"][0],1) correlation,pval = scipy.stats.pearsonr(raster_plots["or_suppression"][1],raster_plots["or_suppression"][0]) pylab.scatter(raster_plots["or_suppression"][1],raster_plots["or_suppression"][0],s=18, facecolor = 'r',lw = 0) pylab.plot(raster_plots["or_suppression"][1],m*numpy.array(raster_plots["or_suppression"][1])+b,'-k',linewidth=2) disable_top_right_axis(ax) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.ylabel('Orientation-contrast suppression', fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax = pylab.subplot(gs[0,1]) m,b = numpy.polyfit(raster_plots["SSI"][1],raster_plots["SSI"][0],1) correlation,pval = scipy.stats.pearsonr(raster_plots["SSI"][1],raster_plots["SSI"][0]) pylab.scatter(raster_plots["SSI"][1],raster_plots["SSI"][0],s=18, facecolor = 'r',lw = 0) pylab.plot(raster_plots["SSI"][1],m*numpy.array(raster_plots["SSI"][1])+b,'-k',linewidth=2) disable_top_right_axis(ax) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.ylabel('Surround selectivity index', fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) print raster_plots.keys() ax = pylab.subplot(gs[1,0]) m,b = numpy.polyfit(raster_plots["suppresion_index"][1],raster_plots["suppresion_index"][0],1) correlation,pval = scipy.stats.pearsonr(raster_plots["suppresion_index"][1],raster_plots["suppresion_index"][0]) pylab.scatter(raster_plots["suppresion_index"][1],raster_plots["suppresion_index"][0],s=18, facecolor = 'r',lw = 0) pylab.plot(raster_plots["suppresion_index"][1],m*numpy.array(raster_plots["suppresion_index"][1])+b,'-k',linewidth=2) disable_top_right_axis(ax) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.ylabel('Suppression index', fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax = pylab.subplot(gs[1,1]) m,b = numpy.polyfit(raster_plots["counter_suppresion_index"][1],raster_plots["counter_suppresion_index"][0],1) correlation,pval = scipy.stats.pearsonr(raster_plots["counter_suppresion_index"][1],raster_plots["counter_suppresion_index"][0]) pylab.scatter(raster_plots["counter_suppresion_index"][1],raster_plots["counter_suppresion_index"][0],s=18, facecolor = 'r',lw = 0) pylab.plot(raster_plots["counter_suppresion_index"][1],m*numpy.array(raster_plots["counter_suppresion_index"][1])+b,'-k',linewidth=2) disable_top_right_axis(ax) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.ylabel('Counter suppression index', fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax = pylab.subplot(gs[2,0]) pylab.scatter(self.lhi.ravel(),self.MR.ravel()*2,s=3, facecolor = 'r',lw = 0) #xx,z = running_average(self.lhi.ravel(),self.MR.ravel()*2) #pylab.plot(xx,z,'k',lw=3.0) disable_top_right_axis(ax) pylab.xlabel('Local homogeneity index', fontsize=20) pylab.ylabel('Modulation ratio', fontsize=20) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax = pylab.subplot(gs[2,1]) pylab.scatter(self.lhi.ravel(),self.OS.ravel(),s=3, facecolor = 'r',lw = 0) #xx,z = running_average(self.lhi.ravel(),self.OS.ravel()) #pylab.plot(xx,z,'k',lw=3.0) disable_top_right_axis(ax) ax.xaxis.set_major_locator(MaxNLocator(4)) ax.yaxis.set_major_locator(MaxNLocator(4)) pylab.xlabel('Local homogeneity index', fontsize=20) pylab.ylabel('Orientation selectivity', fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) print scipy.stats.pearsonr(self.lhi.ravel(),self.OS.ravel()) print scipy.stats.pearsonr(self.lhi.ravel(),self.MR.ravel()*2) release_fig("CorrelationFigure")
def do_plot(plotfile, component, component2, outFile, log, minval, maxval, minval2, maxval2, eps, dpi, origin, annotation, particles, time_ind): # plotfile plotfile to read data from # component first variable to plot # component2 optional second variable to plot # outFile save plot as "outFile" # log (= 1,0) plot log (base 10) of the data # minval (float) specify minimum data range for plot # maxval (float) specify maximum data range for plot # eps (= 1,0) make an EPS plot instead of PNG # dpi (int) (PNG only) make the plot with dpi value # origin (= 1,0) (3-d only) slice through origin (0,0,0) # annotation (2-d only) add annotation string under time # particles (2-d only) particle data # time_ind array index of time cooresponding to plotfile #---------------------- # check incoming values: #----------------------- if (plotfile == ""): print "\n---ERROR: plotfile not specified---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (component == ""): print "\n---ERROR: no component specified---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if ((log != 1) and (log != 0)): print "\n---ERROR: invalid value for log (= 1,0)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if ((eps != 1) and (eps != 0)): print "\n---ERROR: invalid value for eps (= 1,0)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (minval != None): try: minval = float(minval) except ValueError: print "\n---ERROR: invalid value for minval (= float)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (maxval != None): try: maxval = float(maxval) except ValueError: print "\n---ERROR: invalid value for maxval (= float)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (minval2 != None): try: minval2 = float(minval2) except ValueError: print "\n---ERROR: invalid value for minval2 (= float)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (maxval2 != None): try: maxval2 = float(maxval2) except ValueError: print "\n---ERROR: invalid value for maxval2 (= float)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if ((origin != 1) and (origin != 0)): print "\n---ERROR: invalid value for origin (= 1,0)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) if (dpi != None): try: dpi = int(dpi) except ValueError: print "\n---ERROR: invalid value for dpi (= int)---" print " (plotsinglevar_parts.py)\n" usage() sys.exit(2) #-------------------------------------------------------------------------- # construct the output file name #-------------------------------------------------------------------------- if (outFile == ""): outFile = os.path.normpath(plotfile) + "_" + component if (not component2 == ""): outFile += "_" + component2 if (not eps): outFile += ".png" else: outFile += ".eps" else: # make sure the proper extension is used if (not eps): if (not string.rfind(outFile, ".png") > 0): outFile = outFile + ".png" else: if (not string.rfind(outFile, ".eps") > 0): outFile = outFile + ".eps" #-------------------------------------------------------------------------- # read in the meta-data from the plotfile #-------------------------------------------------------------------------- (nx, ny, nz) = fsnapshot.fplotfile_get_size(plotfile) time = fsnapshot.fplotfile_get_time(plotfile) (xmin, xmax, ymin, ymax, zmin, zmax) = \ fsnapshot.fplotfile_get_limits(plotfile) x = xmin + numpy.arange( (nx), dtype=numpy.float64 )*(xmax - xmin)/nx y = ymin + numpy.arange( (ny), dtype=numpy.float64 )*(ymax - ymin)/ny if (nz > 0): z = zmin + numpy.arange( (nz), dtype=numpy.float64 )*(zmax - zmin)/nz if (nz == -1): #---------------------------------------------------------------------- # 2-d plots #---------------------------------------------------------------------- extent = xmin, xmax, ymin, ymax # read in the main component data = numpy.zeros( (nx, ny), dtype=numpy.float64) (data, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) if (minval == None): minval = numpy.min(data) if (maxval == None): maxval = numpy.max(data) # read in the component #2, if present if (not component2 == ""): data2 = numpy.zeros( (nx, ny), dtype=numpy.float64) (data2, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component2, data2) if (not err == 0): sys.exit(2) data2 = numpy.transpose(data2) if (minval2 == None): minval2 = numpy.min(data2) if (maxval2 == None): maxval2 = numpy.max(data2) if log: data = numpy.log10(data) if (not component2 == ""): data2 = numpy.log10(data2) minval2 = math.log10(minval2) maxval2 = math.log10(maxval2) minval = math.log10(minval) maxval = math.log10(maxval) #---------------------------------------------------------------------- # plot main component #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1,2,1) pylab.subplots_adjust(wspace=0.5) else: ax = pylab.subplot(1,1,1) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im=pylab.imshow(data,origin='lower', extent=extent, vmin=minval, vmax=maxval) #---------------------------------------------------------------------- # plot the particle data #---------------------------------------------------------------------- n=0 while(n < len(particles)): # sometimes the length of particle history is larger than index if (time_ind < len(particles[n].history)): pylab.scatter(particles[n].history[time_ind].xyz[0], particles[n].history[time_ind].xyz[1], s=0.5,c='black',marker='o') n += 1 pylab.title(component) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) # make space for a colorbar -- getting it the same size as the # vertical extent of the plot is surprisingly tricky. See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note #---------------------------------------------------------------------- # plot component #2 #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1,2,2) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im = pylab.imshow(data2, origin='lower', extent=extent, vmin=minval2, vmax=maxval2) #---------------------------------------------------------------- # plot the particle data #---------------------------------------------------------------- n=0 while(n < len(particles)): # sometimes the length of particle history is larger than index if (time_ind < len(particles[n].history)): pylab.scatter(particles[n].history[time_ind].xyz[0], particles[n].history[time_ind].xyz[1], s=0.5,c='black',marker='o') n += 1 pylab.title(component2) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) # make space for a colorbar -- getting it the same size as # the vertical extent of the plot is surprisingly tricky. # See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note the # offsetText is the 10^N that appears at the top of the y-axis. cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cb.ax.yaxis.offsetText.set_fontsize("small") #ax_cb.yaxis.tick_right() else: #---------------------------------------------------------------------- # 3-d plot #---------------------------------------------------------------------- ################################### # NOT SUPPORTED YET ################################### print "\n\n--- ERROR: 3-d not yet implemented ---" print " (plotsinglevar_parts.py)\n" sys.exit(2) # figure out the maximum width -- we will plot xy, xz, and yz w1 = xmax - xmin # also w2 w3 = ymax - ymin if (w3 > w1): scale = w3 else: scale = w1 # starting points for the figure positions # assume that the width of the plotting area is 0.05 to 0.95, # leaving 0.9 to be split amongst the 3 plots. So each has a # width of 0.3 # for the height, we will assume that the colorbar at the # bottom gets 0.15, and that we go until 0.95, leaving 0.8 of # height for the plots. pos1 = [0.05, 0.15, 0.3, 0.8] pos2 = [0.35, 0.15, 0.3, 0.8] pos3 = [0.65, 0.15, 0.3, 0.8] fig = pylab.figure() # x-y extent = xmin, xmax, ymin, ymax # read in the main component data = numpy.zeros( (nx, ny), dtype=numpy.float64) indir = 3 (data, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, indir, origin, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) if log: data = numpy.log10(data) if (not minval == None): minval = math.log10(minval) if (not maxval == None): maxval = math.log10(maxval) ax = pylab.subplot(1,3,1) pylab.subplots_adjust(wspace=0.4) #fig.add_axes(pos1) im=pylab.imshow(data,origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos1) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # do a fixed offset in pixels from the (xmin,ymin) data point fig1 = ax.get_figure() trans=matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.5, fig=fig1, units='inches') pylab.text(xmin, ymin, "time = %7.3g s" % (time), verticalalignment="bottom", transform = trans, clip_on=False, fontsize=10) # x-z extent = xmin, xmax, zmin, zmax # read in the main component data = numpy.zeros( (nx, nz), dtype=numpy.float64) (data, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 2, origin, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) if log: data = numpy.log10(data) if (not minval == None): minval = math.log10(minval) if (not maxval == None): maxval = math.log10(maxval) ax = pylab.subplot(1,3,2) #fig.add_axes(pos2) im=pylab.imshow(data,origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos2) pylab.xlabel("x") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # y-z extent = ymin, ymax, zmin, zmax # read in the main component data = numpy.zeros( (ny, nz), dtype=numpy.float64) (data, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 1, origin, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) if log: data = numpy.log10(data) if (not minval == None): minval = math.log10(minval) if (not maxval == None): maxval = math.log10(maxval) ax = pylab.subplot(1,3,3) #fig.add_axes(pos3) im=pylab.imshow(data,origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos3) pylab.xlabel("y") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # colorbar pylab.subplots_adjust(bottom=0.1, left=0.05, right=0.95) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cax = pylab.axes([0.05, 0.06, 0.9, 0.04]) pylab.colorbar(orientation="horizontal", cax=cax, format=formatter) pylab.title(component) #-------------------------------------------------------------------------- # save the figure #-------------------------------------------------------------------------- if (not eps): pylab.savefig(outFile, bbox_inches='tight', dpi=dpi, pad_inches=0.33) else: pylab.savefig(outFile, bbox_inches='tight', pad_inches=0.33)
def plot_orientation_contrast_tuning(self, xindex, yindex,string,independent=True): if independent: fig = pylab.figure() colors=['red','blue','green','purple','orange','black','yellow'] orientation = self.data_dict[(xindex,yindex)]["OCT"]["ORTC"]["info"]["pref_or"] measurment = self.data_dict[(xindex,yindex)]["OCT"] i = 0 m = 0 for curve_label in measurment.keys(): #if curve_label != 'Contrastsurround = 100%': curve = measurment[curve_label]["data"] x_values = sorted(curve.keys()) y_values = [] for k in x_values: y_values.append(curve[k].view()[0][xindex, yindex]) if curve_label != 'ORTC': z = [] ks = sorted(measurment["ORTC"]["data"].keys()) for k in ks: z.append(measurment["ORTC"]["data"][k].view()[0][xindex, yindex]) ssi = self.calculate_octc_selectivity(2*x_values,numpy.max(z)-y_values) self.data_dict[(xindex,yindex)]["OCT"][curve_label]["measures"]["SSI"]=ssi #self.data_dict[(xindex,yindex)]["OCT"]['Contrastsurround = 100%']["measures"]["SSI"]=ssi x_values=numpy.array(x_values)-orientation for j in xrange(0,len(x_values)): if x_values[j] > numpy.pi/2.0: x_values[j] -= numpy.pi if x_values[j] < -numpy.pi/2.0: x_values[j] += numpy.pi for j in xrange(0,len(x_values)): if x_values[j] > numpy.pi/2.0: x_values[j] -= numpy.pi if x_values[j] < -numpy.pi/2.0: x_values[j] += numpy.pi inds = numpy.argsort(x_values) y_values = numpy.take(y_values, inds) x_values = sorted(x_values) #numpy.append(y_values,y_values[0]) #numpy.append(x_values,x_values[0]+numpy.pi) if x_values[0] == -numpy.pi/2: y_values = numpy.append(y_values,[y_values[0]]) x_values = numpy.append(x_values,[numpy.pi/2]) else: y_values = numpy.append([y_values[-1]],y_values) x_values = numpy.append([-numpy.pi/2],x_values) m = max(m,max(y_values)) pylab.plot(x_values, y_values, lw=3, color=colors[i],label=curve_label) i+=1 disable_top_right_axis(pylab.gca()) ax = pylab.gca() pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) ax.set_xlim(-numpy.pi/2-0.2,numpy.pi/2.0+0.2) ax.set_xticks([-numpy.pi/2,0,numpy.pi/2.0]) #ax.set_xticklabels([r'-$\frac{\mathrm{\mathsf{\pi}}{2}$',r'0',r'$\frac{\mathrm{\mathsf{\pi}}{2}$'], fontProperties) # get ceil at first decimal point m = numpy.ceil(m) ax.set_yticks([0.1,m/2,m]) ax.set_yticklabels(ax.get_yticks(), fontProperties) #ax.set_ylim(0.1,m) #pylab.show() if independent: release_fig("OCTC[" + str(xindex) + "," + str(yindex) + "] " + string)
change_axis.text(species_idx, -len(gene_changes) - 3, '*', fontsize=4) m = change_axis.scatter([200], [1], c=[0], vmin=0, vmax=vmax, cmap=cmap, marker='^') cbar = fig.colorbar(m, cax=cax, orientation='vertical', ticks=[0, 1, 2, 3]) cbar.set_ticklabels(['$1$', '$10$', '$10^{2}$', '$10^{3}$']) cbar.set_label('Number of changes', rotation=270, labelpad=10) cl = pylab.getp(cbar.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=9) #fig.text(0.945,0.05,'$\\pi/\\pi_0$',fontsize=12) cbar.ax.tick_params(labelsize=5) change_axis.text(20, 25, 'SNVs', fontsize=5) change_axis.text(20, -20, 'Genes', fontsize=5) ###### # # Distribution of nucleotide changes # ###### pooled_snp_change_distribution = numpy.array(pooled_snp_change_distribution) pooled_between_snp_change_distribution = numpy.array(
sys.stderr.write("Calculating total fixation matrix...\n") fixation_matrix_all, fixation_opportunities_all = diversity_utils.calculate_fixation_matrix(allele_counts_map, passed_sites_map, min_change=min_change) sys.stderr.write("Done!\n") # Calculate fraction nonsynonymous dN = fixation_matrix_non/fixation_opportunities_non dS = fixation_matrix_syn/fixation_opportunities_syn dNplusdS = (dN+dS) fraction_nonsynonymous = dN/(dNplusdS+(dNplusdS==0)) # Calculate total divergence dtot = fixation_matrix_all/fixation_opportunities_all # Calculate which pairs of idxs belong to the same sample, which to the same subject # and which to different subjects same_sample_idxs, same_subject_idxs, diff_subject_idxs = parse_midas_data.calculate_subject_pairs(subject_sample_map, desired_samples) line, = main_axis.semilogx(dtot[diff_subject_idxs], fraction_nonsynonymous[diff_subject_idxs],'.',markersize=2,alpha=0.5,markeredgewidth=0.0) colorVal = pylab.getp(line,'color') main_axis.semilogx(dtot[same_subject_idxs], fraction_nonsynonymous[same_subject_idxs],'s',alpha=0.5,markersize=2,color=colorVal,markeredgewidth=0.0) legend_axis.plot([-2,-1],[-2,-1],'.',markersize=3,alpha=0.5,markeredgewidth=0.0, label=species_label) legend_axis.legend(loc='upper center',frameon=False,fontsize=5,numpoints=1,ncol=1,handlelength=1) pylab.savefig('%s/%s_genus_dNdS_vs_dS.pdf' % (parse_midas_data.analysis_directory,genus_name),bbox_inches='tight') pylab.savefig('%s/%s_genus_dNdS_vs_dS.png' % (parse_midas_data.analysis_directory,genus_name),bbox_inches='tight')
mutator_mut_axis.set_xlim([-1000,61000]) mutator_mut_axis.set_xticks([0,60000]) mutator_mut_axis.set_xticklabels(['0','60k']) mutator_mut_axis.set_ylim([0,3000]) mutator_mut_axis.set_yticks([0,3000]) mutator_mut_axis.set_yticklabels(['0','3k']) mutator_mut_axis.tick_params(axis='y',length=3,pad=1,labelsize=5) mutator_mut_axis.tick_params(axis='x', length=3,pad=1,labelsize=5) mutator_mut_axis.fill_between(numpy.array([0,61000]),numpy.array([0,0]), numpy.array([3000,3000]),color='w',zorder=20) cl = pylab.getp(mutator_mut_axis, 'xmajorticklabels') pylab.setp(cl, fontsize=5) cl = pylab.getp(mutator_mut_axis, 'ymajorticklabels') pylab.setp(cl, fontsize=5) mutator_mut_axis.get_yaxis().tick_left() mutator_mut_axis.get_xaxis().tick_bottom() [i.set_linewidth(0.75) for i in mutator_mut_axis.spines.itervalues()] # Moved these down so that it will work better? mut_axis.tick_params(axis='y', direction='out',length=3,pad=1,labelsize=5) mut_axis.tick_params(axis='x', direction='out',length=3,pad=1,labelsize=5) mut_axis.set_ylabel('Mutations, $M(t)$ ',labelpad=-2) ############################# #
def plotConfusion(confusion, grid, title, file_name, inset=None, fudge=16): pylab.figure() axmain = pylab.axes() confusion_cmap_dict = { 'red':( (0.0, 1.0, 1.0), (0.2, 1.0, 0.5), # Missing to Correct Negative (0.4, 0.5, 1.0), # Correct Negative to False Alarm (0.6, 1.0, 1.0), # False Alarm to Miss (0.8, 1.0, 0.0), # Miss to Hit (1.0, 0.0, 0.0), ), 'green':( (0.0, 1.0, 1.0), (0.2, 1.0, 0.5), (0.4, 0.5, 0.0), (0.6, 0.0, 1.0), (0.8, 1.0, 0.5), (1.0, 0.5, 0.5), ), 'blue':( (0.0, 1.0, 1.0), (0.2, 1.0, 0.5), (0.4, 0.5, 1.0), (0.6, 1.0, 0.0), (0.8, 0.0, 0.0), (1.0, 0.0, 0.0), ), } confusion_cmap = LinearSegmentedColormap('confusion', confusion_cmap_dict, 256) tick_labels = [ "Missing", "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ] min_label = -1 xs, ys = grid.getXY() pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1)) tick_locs = np.linspace(-1, min_label + len(tick_labels) - 2, len(tick_labels)) tick_locs += (tick_locs[1] - tick_locs[0]) / 2 bar = pylab.colorbar() bar.locator = FixedLocator(tick_locs) bar.formatter = FixedFormatter(tick_labels) pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large') bar.update_ticks() grid.drawPolitical() if inset: lb_y, lb_x = [ b.start for b in inset ] ub_y, ub_x = [ b.stop + fudge for b in inset ] inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x)) axins = zoomed_inset_axes(pylab.gca(), 2, loc=4) pylab.sca(axins) pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=0, vmax=3) grid.drawPolitical() pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x]) pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
def plot(self, labels=None, numbers=False, origin='upper', numbers_alpha=None, xlabels_vertical=True, numbers_kwargs={}, **kwargs): """Provide presentation of confusion matrix in image Parameters ---------- labels : list of int or str Optionally provided labels guarantee the order of presentation. Also value of None places empty column/row, thus provides visual groupping of labels (Thanks Ingo) numbers : bool Place values inside of confusion matrix elements numbers_alpha : None or float Controls textual output of numbers. If None -- all numbers are plotted in the same intensity. If some float -- it controls alpha level -- higher value would give higher contrast. (good value is 2) origin : str Which left corner diagonal should start xlabels_vertical : bool Either to plot xlabels vertical (benefitial if number of labels is large) numbers_kwargs : dict Additional keyword parameters to be added to numbers (if numbers is True) **kwargs Additional arguments given to imshow (\eg me cmap) Returns ------- (fig, im, cb) -- figure, imshow, colorbar """ externals.exists("pylab", raise_=True) import pylab as pl self.compute() labels_order = labels # some shortcuts labels = self.__labels labels_map = self.__labels_map labels_map_rev = self.__labels_map_rev matrix = self.__matrix # craft original mapping from a label into index in the matrix labels_indexes = dict([(x,i) for i,x in enumerate(labels)]) labels_rev = [] if labels_map_rev is not None: labels_rev = [','.join([str(x) for x in labels_map_rev[l]]) for l in labels] labels_map_full = dict(zip(labels_rev, labels)) if labels_order is not None: labels_order_filtered = filter(lambda x:x is not None, labels_order) labels_order_filtered_set = set(labels_order_filtered) # Verify if all labels provided in labels if set(labels) == labels_order_filtered_set: # We were provided numerical (most probably) set labels_plot = labels_order elif len(labels_rev) \ and set(labels_rev) == labels_order_filtered_set: # not clear if right whenever there were multiple labels # mapped into the same labels_plot = [] for l in labels_order: v = None if l is not None: v = labels_map_full[l] labels_plot += [v] else: raise ValueError, \ "Provided labels %s do not match set of known " \ "original labels (%s) or mapped labels (%s)" % \ (labels_order, labels, labels_rev) else: labels_plot = labels # where we have Nones? isempty = np.array([l is None for l in labels_plot]) non_empty = np.where(np.logical_not(isempty))[0] # numbers of different entries NlabelsNN = len(non_empty) Nlabels = len(labels_plot) if matrix.shape != (NlabelsNN, NlabelsNN): raise ValueError, \ "Number of labels %d doesn't correspond the size" + \ " of a confusion matrix %s" % (NlabelsNN, matrix.shape) confusionmatrix = np.zeros((Nlabels, Nlabels)) mask = confusionmatrix.copy() ticks = [] tick_labels = [] # populate in a silly way reordered_indexes = [labels_indexes[i] for i in labels_plot if i is not None] for i, l in enumerate(labels_plot): if l is not None: j = labels_indexes[l] confusionmatrix[i, non_empty] = matrix[j, reordered_indexes] confusionmatrix[non_empty, i] = matrix[reordered_indexes, j] ticks += [i + 0.5] if labels_map_rev is not None: tick_labels += ['/'.join(labels_map_rev[l])] else: tick_labels += [str(l)] else: mask[i, :] = mask[:, i] = 1 confusionmatrix = np.ma.MaskedArray(confusionmatrix, mask=mask) # turn off automatic update if interactive if pl.matplotlib.get_backend() == 'TkAgg': pl.ioff() fig = pl.gcf() ax = pl.gca() ax.axis('off') # some customization depending on the origin xticks_position, yticks, ybottom = { 'upper': ('top', [Nlabels-x for x in ticks], 0.1), 'lower': ('bottom', ticks, 0.2) }[origin] # Plot axi = fig.add_axes([0.15, ybottom, 0.7, 0.7]) im = axi.imshow(confusionmatrix, interpolation="nearest", origin=origin, aspect='equal', extent=(0, Nlabels, 0, Nlabels), **kwargs) # plot numbers if numbers: numbers_kwargs_ = {'fontsize': 10, 'horizontalalignment': 'center', 'verticalalignment': 'center'} maxv = float(np.max(confusionmatrix)) colors = [im.to_rgba(0), im.to_rgba(maxv)] for i,j in zip(*np.logical_not(mask).nonzero()): v = confusionmatrix[j, i] # scale alpha non-linearly if numbers_alpha is None: alpha = 1.0 else: # scale according to value alpha = 1 - np.array(1 - v / maxv) ** numbers_alpha y = {'lower':j, 'upper':Nlabels-j-1}[origin] numbers_kwargs_['color'] = colors[int(v<maxv/2)] numbers_kwargs_.update(numbers_kwargs) pl.text(i+0.5, y+0.5, '%d' % v, alpha=alpha, **numbers_kwargs_) maxv = np.max(confusionmatrix) boundaries = np.linspace(0, maxv, np.min((maxv, 10)), True) # Label axes pl.xlabel("targets") pl.ylabel("predictions") pl.setp(axi, xticks=ticks, yticks=yticks, xticklabels=tick_labels, yticklabels=tick_labels) axi.xaxis.set_ticks_position(xticks_position) axi.xaxis.set_label_position(xticks_position) if xlabels_vertical: pl.setp(pl.getp(axi, 'xticklabels'), rotation='vertical') axcb = fig.add_axes([0.8, ybottom, 0.02, 0.7]) cb = pl.colorbar(im, cax=axcb, format='%d', ticks = boundaries) if pl.matplotlib.get_backend() == 'TkAgg': pl.ion() pl.draw() # Store it primarily for testing self._plotted_confusionmatrix = confusionmatrix return fig, im, cb
def Figure6(self): self.fig = pylab.figure(facecolor='w',figsize=(14, 12),dpi=800) gs = gridspec.GridSpec(57, 36) gs.update(left=0.05, right=0.95, top=0.95, bottom=0.05,wspace=0.2,hspace=0.2) picked_stcs = [(57,57), (55,51) , (49,51) , (47,55) , (53,59) , (47,61)] ax = pylab.subplot(gs[1:19,9:27]) self.plot_average_size_tuning_curve(independent=False) pylab.ylabel('Normalized response', fontsize=20) ax = pylab.subplot(gs[22:32,1:11]) self.plot_size_tunning(picked_stcs[0][0], picked_stcs[0][1],independent=False) remove_x_tick_labels() pylab.ylabel('Response', fontsize=20) ax = pylab.subplot(gs[22:32,13:23]) self.plot_size_tunning(picked_stcs[1][0], picked_stcs[1][1],independent=False) disable_left_axis(pylab.gca()) remove_x_tick_labels() remove_y_tick_labels() ax = pylab.subplot(gs[22:32,25:35]) self.plot_size_tunning(picked_stcs[2][0], picked_stcs[2][1],independent=False) disable_left_axis(pylab.gca()) remove_x_tick_labels() remove_y_tick_labels() ax = pylab.subplot(gs[34:44,1:11]) self.plot_size_tunning(picked_stcs[3][0], picked_stcs[3][1],independent=False) pylab.ylabel('Response', fontsize=20) ax = pylab.subplot(gs[34:44,13:23]) self.plot_size_tunning(picked_stcs[4][0], picked_stcs[4][1],independent=False) disable_left_axis(pylab.gca()) remove_y_tick_labels() ax = pylab.subplot(gs[34:44,25:35]) self.plot_size_tunning(picked_stcs[5][0], picked_stcs[5][1],independent=False) disable_left_axis(pylab.gca()) remove_y_tick_labels() # PLOT EXPERIMENTAL DATA x,y = zip(*[(-0.0118, 10.3038),(0.0398, 5.0943),(0.1025, 4.8631),(0.2222, 10.5367),(0.3872, 22.694),(0.6212, 21.1903),(0.9463, 25.9388),(1.4487, 16.2168),(2.219, 17.9579),(3.3435, 9.6286),(4.9921, 21.2156)]) ox,oy = zip(*[(0.0447, 25.4706),(0.1181, 49.6678),(0.2268, 41.2169),(0.3803, 55.4581),(0.6206, 39.3668),(0.963, 36.5901),(1.4654, 29.8782),(2.2245, 23.9781),(3.3429, 25.1424),(4.9977, 23.7626)]) x = numpy.array(x) y = numpy.array(y) ox = numpy.array(ox) oy = numpy.array(oy) ax = pylab.subplot(gs[47:57,1:11]) ax.plot(x,y,lw=3,color='r') pylab.hold('on') ax.plot(ox,oy,lw=3,color='b') ax.set_xlim(0,5) ax.set_xticks([0,1,2,3,4,5]) ax.set_ylim(0,80) ax.set_yticks([0,40,80]) ax.set_ylabel('Response', fontsize=20) disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels(pylab.gca().get_xticks(), fontProperties) pylab.gca().set_yticklabels(pylab.gca().get_yticks(), fontProperties) lc_x,lc_y = zip(*[(-0.0487, -0.0419),(1.3979, 6.7485),(2.0126, 8.1943),(2.8208, 10.3224),(3.9922, 4.6368),(5.6557, 3.5735),(7.947, 5.1138),(11.0084, 4.837)]) mc_x,mc_y = zip(*[(-0.0487, -0.0419),(1.347, 13.4836),(1.9927, 15.4864),(2.7962, 13.3683),(4.0149, 8.2393),(5.6128, 7.3489),(7.9576, 7.1724),(11.0201, 6.5096)]) hc_x,hc_y = zip(*[(-0.0487, -0.0419),(1.3515, 17.7727),(1.9832, 12.9988),(2.8384, 9.8502),(4.0052, 5.8375),(5.6352, 11.0801),(7.9759, 12.4049),(10.9943, 9.9844)]) lc_x = numpy.array(lc_x) lc_y = numpy.array(lc_y) mc_x = numpy.array(mc_x) mc_y = numpy.array(mc_y) hc_x = numpy.array(hc_x) hc_y = numpy.array(hc_y) ax = pylab.subplot(gs[47:57,13:23]) ax.plot(lc_x,lc_y,lw=3,color='r') ax.plot(lc_x,mc_y,lw=3,color='g') ax.plot(lc_x,hc_y,lw=3,color='b') ax.set_xlim(0,12) ax.set_xticks([0,5,10]) ax.set_ylim(0,20) ax.set_yticks([0,10,20]) ax.set_ylabel('Response', fontsize=20) disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels(pylab.gca().get_xticks(), fontProperties) pylab.gca().set_yticklabels(pylab.gca().get_yticks(), fontProperties) lc_x,lc_y = zip(*[(0.665, 14.9452),(1.0443, 22.295),(1.5573, 27.5117),(2.2633, 32.0173),(3.3754, 37.7079),(5.2272, 28.233),(7.5956, 30.1319),(11.9241, 32.2685),(17.7866, 40.8027),(26.8654, 43.6499)]) mc_x,mc_y = zip(*[(0.6909, 11.628),(1.0305, 15.8968),(1.5377, 30.3552),(2.2968, 60.2165),(3.5141, 63.0637),(5.2352, 51.9297),(8.1111, 49.5638),(12.0944, 52.4108),(18.0381, 58.8123),(27.2453, 61.6595)]) hc_x,hc_y = zip(*[(0.6827, 25.3719),(1.0312, 27.745),(1.5594, 48.6018),(2.3, 82.0174),(3.5202, 89.604),(5.3143, 84.6312),(8.0208, 75.867),(12.1168, 81.0838),(18.5382, 83.4571),(27.2836, 83.4604)]) lc_x = numpy.array(lc_x) lc_y = numpy.array(lc_y) mc_x = numpy.array(mc_x) mc_y = numpy.array(mc_y) hc_x = numpy.array(hc_x) hc_y = numpy.array(hc_y) ax = pylab.subplot(gs[47:57,25:35]) ax.semilogx(lc_x,lc_y,lw=3,color='r') ax.semilogx(lc_x,mc_y,lw=3,color='g') ax.semilogx(lc_x,hc_y,lw=3,color='b') ax.set_xlim(0.6,30) ax.set_xticks([0.5,1.0,3.0,10,50]) ax.set_ylim(0,100) ax.set_yticks([0.0,50.0,100]) ax.set_ylabel('Response', fontsize=20) disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels(pylab.gca().get_xticks(), fontProperties) pylab.gca().set_yticklabels(pylab.gca().get_yticks(), fontProperties) release_fig("Figure6")
def do_plot(plotfile, component, component2, outFile, log, minval, maxval, minval2, maxval2, eps, dpi, origin, annotation, xmin_pass, ymin_pass, zmin_pass, xmax_pass, ymax_pass, zmax_pass): pylab.rc("font", size=9) #-------------------------------------------------------------------------- # construct the output file name #-------------------------------------------------------------------------- if (outFile == ""): outFile = os.path.normpath(plotfile) + "_" + component if (not component2 == ""): outFile += "_" + component2 if (not eps): outFile += ".png" else: outFile += ".eps" else: # make sure the proper extension is used if (not eps): if (not string.rfind(outFile, ".png") > 0): outFile = outFile + ".png" else: if (not string.rfind(outFile, ".eps") > 0): outFile = outFile + ".eps" #-------------------------------------------------------------------------- # read in the meta-data from the plotfile #-------------------------------------------------------------------------- (nx, ny, nz) = fsnapshot.fplotfile_get_size(plotfile) time = fsnapshot.fplotfile_get_time(plotfile) (xmin, xmax, ymin, ymax, zmin, zmax) = \ fsnapshot.fplotfile_get_limits(plotfile) dx = (xmax - xmin) / nx x = xmin + numpy.arange((nx), dtype=numpy.float64) * dx dy = (ymax - ymin) / ny y = ymin + numpy.arange((ny), dtype=numpy.float64) * dy if (nz > 0): dz = (zmax - zmin) / nz z = zmin + numpy.arange((nz), dtype=numpy.float64) * dz if (nz == -1): #---------------------------------------------------------------------- # 2-d plots #---------------------------------------------------------------------- extent = [xmin, xmax, ymin, ymax] ix0 = 0 ix = nx iy0 = 0 iy = ny if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not ymin_pass == None): extent[2] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not ymax_pass == None): extent[3] = ymax_pass iy = int((ymax_pass - ymin) / dy) sparseX = 0 if (ny >= 3 * nx): sparseX = 1 # read in the main component data = numpy.zeros((nx, ny), dtype=numpy.float64) (data, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) # read in the component #2, if present if (not component2 == ""): data2 = numpy.zeros((nx, ny), dtype=numpy.float64) (data2, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component2, data2) if (not err == 0): sys.exit(2) data2 = numpy.transpose(data2) # log? if log: if (numpy.min(data) < 0): data = numpy.log10(numpy.abs(data)) else: data = numpy.log10(data) if (not component2 == ""): if (numpy.min(data2) < 0.0): data2 = numpy.log10(numpy.abs(data2)) else: data2 = numpy.log10(data2) if (not minval == None): minval = math.log10(minval) if (not maxval == None): maxval = math.log10(maxval) if (not minval2 == None): minval2 = math.log10(minval2) if (not maxval2 == None): maxval2 = math.log10(maxval2) #---------------------------------------------------------------------- # plot main component #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1, 2, 1) pylab.subplots_adjust(wspace=0.5) else: ax = pylab.subplot(1, 1, 1) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im = pylab.imshow(data[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval) pylab.title(component) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) if (sparseX): ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) # make space for a colorbar -- getting it the same size as the # vertical extent of the plot is surprisingly tricky. See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note # the offsetText is the 10^N that appears at the top of the # y-axis. cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cb.ax.yaxis.offsetText.set_fontsize("small") # do a fixed offset in pixels from the (xmin,ymin) data point trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.5, fig=fig1, units='inches') pylab.text(xmin, ymin, "time = %7.3g s" % (time), verticalalignment="bottom", transform=trans, clip_on=False, fontsize=10) if (not annotation == ""): trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.65, fig=fig1, units='inches') pylab.text(xmin, ymin, "%s" % (annotation), verticalalignment="bottom", transform=trans, clip_on=False, fontsize=10) #---------------------------------------------------------------------- # plot component #2 #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1, 2, 2) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im = pylab.imshow(data2[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval2, vmax=maxval2) pylab.title(component2) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax.xaxis.set_major_formatter( pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter( pylab.ScalarFormatter(useMathText=True)) if (sparseX): ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) # make space for a colorbar -- getting it the same size as # the vertical extent of the plot is surprisingly tricky. # See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note the # offsetText is the 10^N that appears at the top of the y-axis. cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cb.ax.yaxis.offsetText.set_fontsize("small") #ax_cb.yaxis.tick_right() else: #---------------------------------------------------------------------- # 3-d plot #---------------------------------------------------------------------- # starting points for the figure positions # assume that the width of the plotting area is 0.05 to 0.95, # leaving 0.9 to be split amongst the 3 plots. So each has a # width of 0.3 # for the height, we will assume that the colorbar at the # bottom gets 0.15, and that we go until 0.95, leaving 0.8 of # height for the plots. pos1 = [0.05, 0.15, 0.3, 0.8] pos2 = [0.35, 0.15, 0.3, 0.8] pos3 = [0.65, 0.15, 0.3, 0.8] fig = pylab.figure() # read in the slices # x-y data_xy = numpy.zeros((nx, ny), dtype=numpy.float64) indir = 3 (data_xy, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, indir, origin, data_xy) if (not err == 0): sys.exit(2) data_xy = numpy.transpose(data_xy) if log: if (numpy.min(data_xy) < 0): data_xy = numpy.log10(numpy.abs(data_xy)) else: data_xy = numpy.log10(data_xy) # x-z data_xz = numpy.zeros((nx, nz), dtype=numpy.float64) (data_xz, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 2, origin, data_xz) if (not err == 0): sys.exit(2) data_xz = numpy.transpose(data_xz) if log: if (numpy.min(data_xz) < 0): data_xz = numpy.log10(numpy.abs(data_xz)) else: data_xz = numpy.log10(data_xz) # y-z data_yz = numpy.zeros((ny, nz), dtype=numpy.float64) (data_yz, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 1, origin, data_yz) if (not err == 0): sys.exit(2) data_yz = numpy.transpose(data_yz) if log: if (numpy.min(data_yz) < 0): data_yz = numpy.log10(numpy.abs(data_yz)) else: data_yz = numpy.log10(data_yz) if (not minval == None): if (log): minval = math.log10(minval) else: minval = numpy.min(data_xy) minval = min(minval, numpy.min(data_xz)) minval = min(minval, numpy.min(data_yz)) if (not maxval == None): if (log): maxval = math.log10(maxval) else: maxval = numpy.max(data_xy) maxval = max(maxval, numpy.max(data_xz)) maxval = max(maxval, numpy.max(data_yz)) # x-y extent = [xmin, xmax, ymin, ymax] ix0 = 0 ix = nx iy0 = 0 iy = ny if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not ymin_pass == None): extent[2] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not ymax_pass == None): extent[3] = ymax_pass iy = int((ymax_pass - ymin) / dy) ax = pylab.subplot(1, 3, 1) pylab.subplots_adjust(wspace=0.4) #fig.add_axes(pos1) im = pylab.imshow(data_xy[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos1) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # do a fixed offset in pixels from the (xmin,ymin) data point fig1 = ax.get_figure() trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.5, fig=fig1, units='inches') # pylab.text(xmin_pass, ymin_pass, "time = %7.3g s" % (time), # verticalalignment="bottom", transform = trans, # clip_on=False, fontsize=10) # x-z extent = [xmin, xmax, zmin, zmax] ix0 = 0 ix = nx iz0 = 0 iz = nz if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not zmin_pass == None): extent[2] = zmin_pass iz0 = int((zmin_pass - zmin) / dz) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not zmax_pass == None): extent[3] = zmax_pass iz = int((zmax_pass - zmin) / dz) ax = pylab.subplot(1, 3, 2) #fig.add_axes(pos2) im = pylab.imshow(data_xz[iz0:iz, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos2) pylab.xlabel("x") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # y-z extent = [ymin, ymax, zmin, zmax] iy0 = 0 iy = ny iz0 = 0 iz = nz if (not ymin_pass == None): extent[0] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not zmin_pass == None): extent[2] = zmin_pass iz0 = int((zmin_pass - zmin) / dz) if (not ymax_pass == None): extent[1] = ymax_pass iy = int((ymax_pass - ymin) / dy) if (not zmax_pass == None): extent[3] = zmax_pass iz = int((zmax_pass - zmin) / dz) ax = pylab.subplot(1, 3, 3) #fig.add_axes(pos3) im = pylab.imshow(data_yz[iz0:iz, iy0:iy], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos3) pylab.xlabel("y") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # colorbar pylab.subplots_adjust(bottom=0.1, left=0.05, right=0.95) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cax = pylab.axes([0.05, 0.06, 0.9, 0.04]) pylab.colorbar(orientation="horizontal", cax=cax, format=formatter) pylab.title(component) #-------------------------------------------------------------------------- # save the figure #-------------------------------------------------------------------------- # try: pylab.tight_layout() # requires matplotlib >= 1.1 # except: # pass if (not eps): pylab.savefig(outFile, bbox_inches='tight', dpi=dpi, pad_inches=0.33) else: pylab.savefig(outFile) #, bbox_inches='tight', pad_inches=0.33)
def plot_average_size_tuning_curve(self,independent=True): if independent: fig = pylab.figure() average_curves={} sem_curves={} curves={} for k in self.data_dict.keys(): # find maximum for the curves m = [] for curve_label in self.data_dict[k]["ST"].keys(): xindex, yindex = k curve = self.data_dict[k]["ST"][curve_label]["data"] x_values = sorted(curve.keys()) m.append(numpy.max([curve[key].view()[0][xindex, yindex] for key in x_values])) m = numpy.max(m) for curve_label in self.data_dict[k]["ST"].keys(): xindex, yindex = k curve = self.data_dict[k]["ST"][curve_label]["data"] x_values = sorted(curve.keys()) y_values = [curve[key].view()[0][xindex, yindex] for key in x_values] # normalize curve y_values = y_values / m if curves.has_key(curve_label): curves[curve_label].append(numpy.array(y_values)) else: curves[curve_label]=[numpy.array(y_values)] for curve_label in curves: average_curves[curve_label]=numpy.mean(numpy.array(curves[curve_label]),axis=0) sem_curves[curve_label]=scipy.stats.sem(numpy.array(curves[curve_label]),axis=0) colors=['red','blue'] i=0 for curve_label in average_curves: pylab.plot(x_values, average_curves[curve_label]*100, lw=3, color=colors[i]) pylab.errorbar(x_values, average_curves[curve_label]*100, lw=1, ecolor=colors[i], yerr=sem_curves[curve_label]*100, fmt=None) pylab.xticks([0,numpy.max(x_values)/2,numpy.max(x_values)]) pylab.yticks([0,50,100]) pylab.gca().set_yticklabels(['0%','50%','100%']) pylab.xlim(-0.1,numpy.max(x_values)+0.1) pylab.ylim(0,100) i=i+1 disable_top_right_axis(pylab.gca()) pylab.setp(pylab.getp(pylab.gca(), 'xticklabels'), fontsize=20) pylab.setp(pylab.getp(pylab.gca(), 'yticklabels'), fontsize=20) pylab.gca().set_xticklabels(pylab.gca().get_xticks(), fontProperties) pylab.gca().set_yticklabels(pylab.gca().get_yticks(), fontProperties) if independent: release_fig("AverageSTC")