def _update3(itr,D,x,soln,t,ax,time): N = 100 #ax.clear() buff = 200.0 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) ax.set_xlim((minx-buff/2,maxx+buff/2)) ax.set_ylim((miny-buff/2,maxy+buff/2)) square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() ax.images = [] im =NonUniformImage(ax,interpolation='bilinear', cmap='cubehelix', extent=(minx,maxx,miny,maxy)) val = soln[itr](zip(xflat,yflat)) val = np.sqrt(np.sum(val**2,1)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) t.set_text('t: %s s' % time[itr]) return ax,t
def plot_spectrogram(spec, Xd=(0,1), Yd=(0,1)): import matplotlib #matplotlib.use('GTKAgg') import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.image import NonUniformImage import matplotlib.colors as colo # x_min, x_max = Xd y_min, y_max = Yd # fig = plt.figure() nf = len(spec) for ch, data in enumerate(spec): #print ch, data.shape x = numpy.linspace(x_min, x_max, data.shape[0]) y = numpy.linspace(y_min, y_max, data.shape[1]) #print x[0],x[-1],y[0],y[-1] ax = fig.add_subplot(nf*100+11+ch) im = NonUniformImage(ax, interpolation='bilinear', cmap=cm.gray_r, norm=colo.LogNorm(vmin=.00001)) im.set_data(x, y, data.T) ax.images.append(im) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title('Channel %d' % ch) #ax.set_xlabel('timeline') ax.set_ylabel('frequency') print 'Statistics: max<%.3f> min<%.3f> mean<%.3f> median<%.3f>' % (data.max(), data.min(), data.mean(), numpy.median(data)) # plt.show()
def _do_plot2(x, y, z, fname, min_pitch): fig = figure(figsize=(15,7.5+7.5/2)) #fig.suptitle('Narmour') ax = fig.add_subplot(111) im = NonUniformImage(ax, interpolation=None, extent=(min(x)-1, max(x)+1, min(y)-1, max(y)+1)) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(min(x)-1, max(x)+1) ax.set_ylim(min(y)-1, max(y)+1) def format_pitch(i, pos=None): if int(i) != i: import ipdb;ipdb.set_trace() return Note(int(i + min_pitch)%12).get_pitch_name()[:-1] ax.set_xlabel('Segunda nota') ax.axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_pitch)) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(base=1.0)) ax.set_ylabel('Primer nota') ax.axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_pitch)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator()) cb = plt.colorbar(im) pylab.grid(True) pylab.savefig(fname) pylab.close()
def sec_show(coord, depth, data, axe, cmap='viridis', coord_type='lon'): """ plot data on the axe, mix between imshow and contour return the colorbar, so user can add a label """ depth = -np.abs(depth) # to be sure that depth is negative im = NonUniformImage(axe, interpolation='nearest', \ extent=(np.nanmin(coord), np.nanmax(coord), \ np.nanmin(depth), np.nanmax(depth)), \ cmap=cmap) # we need to reverse order of array so everything goes increasing # xx,yy=np.meshgrid(coord,depth) # contours = plt.contour(xx,yy, data.T, 3, colors='black') # plt.clabel(contours, inline=True, fontsize=8) im.set_data(coord, depth[::-1], data.T[::-1, :]) axe.images.append(im) axe.set_xlim(np.nanmin(coord), np.nanmax(coord)) axe.set_ylim(np.nanmin(depth), np.nanmax(depth)) axe.set_ylabel('Depth (m)') axe.set_xlabel(coord_type + u' ($^{\circ}$ E)') # adding colorbar cb = plt.colorbar(im, ax=axe, extend='both') # printing scale with positive depth axe.set_yticklabels(np.abs([int(i) for i in axe.get_yticks()])) return cb
def plot_spectrogram(spec, Xd=(0, 1), Yd=(0, 1), norm=colo.LogNorm(vmin=0.000001), figname=None): # x_min, x_max = Xd y_min, y_max = Yd # fig = plt.figure(num=figname) nf = len(spec) for ch, data in enumerate(spec): #print ch, data.shape x = np.linspace(x_min, x_max, data.shape[0]) y = np.linspace(y_min, y_max, data.shape[1]) #print x[0],x[-1],y[0],y[-1] ax = fig.add_subplot(nf * 100 + 11 + ch) im = NonUniformImage(ax, interpolation='bilinear', cmap=cm.gray_r, norm=norm) im.set_data(x, y, data.T) ax.images.append(im) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title('Channel %d' % ch) #ax.set_xlabel('timeline') ax.set_ylabel('frequency') print 'Statistics: max<%.3f> min<%.3f> mean<%.3f> median<%.3f>' % ( data.max(), data.min(), data.mean(), np.median(data)) # plt.show()
def plotDensity(ax, x, result): N = len(result["moments"][0]) y = np.linspace(0, 1, len(result["density"][0])) z = np.log(1 + np.array(zip(*result["density"]))) im = NonUniformImage(ax, norm=Normalize(0, 5, clip=True), interpolation="nearest", cmap=cm.Greys) im.set_data(x, y, z) ax.images.append(im)
def plot_spectrogram(spec, Xd=(0,1), Yd=(0,1), norm=colo.LogNorm(vmin=0.000001), figname=None): # x_min, x_max = Xd y_min, y_max = Yd # fig = plt.figure(num=figname) nf = len(spec) for ch, data in enumerate(spec): #print ch, data.shape x = np.linspace(x_min, x_max, data.shape[0]) y = np.linspace(y_min, y_max, data.shape[1]) #print x[0],x[-1],y[0],y[-1] ax = fig.add_subplot(nf*100+11+ch) im = NonUniformImage(ax, interpolation='bilinear', cmap=cm.gray_r, norm=norm) im.set_data(x, y, data.T) ax.images.append(im) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title('Channel %d' % ch) #ax.set_xlabel('timeline') ax.set_ylabel('frequency') print 'Statistics: max<%.3f> min<%.3f> mean<%.3f> median<%.3f>' % (data.max(), data.min(), data.mean(), np.median(data)) # plt.show()
def test_nonuniformimage_setdata(): ax = plt.gca() im = NonUniformImage(ax) x = np.arange(3, dtype=float) y = np.arange(4, dtype=float) z = np.arange(12, dtype=float).reshape((4, 3)) im.set_data(x, y, z) x[0] = y[0] = z[0, 0] = 9.9 assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed'
def test_nonuniformimage_setdata(): ax = plt.gca() im = NonUniformImage(ax) x = np.arange(3, dtype=np.float64) y = np.arange(4, dtype=np.float64) z = np.arange(12, dtype=np.float64).reshape((4, 3)) im.set_data(x, y, z) x[0] = y[0] = z[0, 0] = 9.9 assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed'
def NonUnifIm(ax, x, y, z, xlab, ylab, **kwargs): im = NonUniformImage(ax, **kwargs) im.set_data(x, y, z) # im.set_clim(vmin=vmin, vmax=vmax) ref = ax.images.append(im) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()]) ax.set_xlabel(xlab) ax.set_ylabel(ylab) return ref, im
def test_nonuniform_and_pcolor(): axs = plt.figure(figsize=(3, 3)).subplots(3, sharex=True, sharey=True) for ax, interpolation in zip(axs, ["nearest", "bilinear"]): im = NonUniformImage(ax, interpolation=interpolation) im.set_data(np.arange(3) ** 2, np.arange(3) ** 2, np.arange(9).reshape((3, 3))) ax.add_image(im) axs[2].pcolorfast( # PcolorImage np.arange(4) ** 2, np.arange(4) ** 2, np.arange(9).reshape((3, 3))) for ax in axs: ax.set_axis_off() # NonUniformImage "leaks" out of extents, not PColorImage. ax.set(xlim=(0, 10))
def show2(mat): clf() ax = gca() from matplotlib.image import NonUniformImage #ax = fig.add_subplot(133, title='NonUniformImage: interpolated', #aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters, ycenters, mat) ax.images.append(im) xlim(xedges[[0, -1]]) ylim(yedges[[0, -1]])
def plot_interpolant(D,interp,x,title='',dim=1,ax=None,scatter=False): if ax is None: fig,ax = plt.subplots() plt.gca().set_aspect('equal', adjustable='box') ax.set_title(title) buff = 400.0 N = 150 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) ax.set_xlim((minx-buff,maxx+buff)) ax.set_ylim((miny-buff,maxy+buff)) if dim == 1: xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() points = np.zeros((len(xflat),2)) points[:,0] = xflat points[:,1] = yflat val = interp(points) #val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0 im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix_r',extent=(minx,maxx,miny,maxy)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) if scatter == True: p = ax.scatter(x[:,0], x[:,1], c='gray',edgecolor='none',zorder=2,s=10) cbar = plt.colorbar(im) if dim == 2: ax.quiver(x[::3,0],x[::3,1],interp(x)[::3,0],interp(x)[::3,1],color='gray',scale=4000.0,zorder=20) return ax
def execute(self): pylab.ioff() self.figure = pylab.figure() self.figure.canvas.mpl_connect('motion_notify_event', self.dataPrinter) x = self.fieldContainer.dimensions[-1].data y = self.fieldContainer.dimensions[-2].data xmin=scipy.amin(x) xmax=scipy.amax(x) ymin=scipy.amin(y) ymax=scipy.amax(y) #Support for images with non uniform axes adapted #from python-matplotlib-doc/examples/pcolor_nonuniform.py ax = self.figure.add_subplot(111) vmin = self.fieldContainer.attributes.get('vmin', None) vmax = self.fieldContainer.attributes.get('vmax', None) if vmin is not None: vmin /= self.fieldContainer.unit if vmax is not None: vmax /= self.fieldContainer.unit if MPL_LT_0_98_1 or self.fieldContainer.isLinearlyDiscretised(): pylab.imshow(self.fieldContainer.maskedData, aspect='auto', interpolation='nearest', vmin=vmin, vmax=vmax, origin='lower', extent=(xmin, xmax, ymin, ymax)) pylab.colorbar(format=F(self.fieldContainer), ax=ax) else: im = NonUniformImage(ax, extent=(xmin,xmax,ymin,ymax)) if vmin is not None or vmax is not None: im.set_clim(vmin, vmax) im.set_data(x, y, self.fieldContainer.maskedData) else: im.set_data(x, y, self.fieldContainer.maskedData) im.autoscale_None() ax.images.append(im) ax.set_xlim(xmin,xmax) ax.set_ylim(ymin,ymax) pylab.colorbar(im,format=F(self.fieldContainer), ax=ax) pylab.xlabel(self.fieldContainer.dimensions[-1].shortlabel) pylab.ylabel(self.fieldContainer.dimensions[-2].shortlabel) pylab.title(self.fieldContainer.label) #ax=pylab.gca() if self.show: pylab.ion() pylab.show()
def Graf_Flujo(Vf, K, l, a, h, H): #Matriz del Marco Mx = int(l / 0.05) LadoMx = np.arange(1, Mx + 1, 1) My = int(a / 0.05) + 1 LadoMy = np.arange(1, My + 1, 1) M = np.ones([My, Mx]) #Extraigo los datos mod = modelo(K, l, a, h) Qs = mod[2] TsFlujo = mod[4] Hi = H Tmin = TsFlujo[Hi - 2] QsAn = Qs[Hi - 1:Hi + 3] #Calor en cada celda Qi = QsAn[0] / (Mx * My) #Incremento de T Tadd = Qi / (Vf) Tper = ((K * Qi) / h) #Primera columna con Tmin for i in range(My): M[i, 0] = Tmin #print(M) #Tfinal en cada celda for j in range(int(My / 2) + 1): for i in range(1, Mx): M[j, i] = M[j, i - 1] + Tadd M[My - 1 - j, i] = M[j, i] M[j] = M[j] - (Tper * (int(My / 2) - j)) M[My - 1 - j] = M[j] #print(M) #grafico del flujo fig, axs = plt.subplots(figsize=(10, 5)) im = NonUniformImage(axs, interpolation='bilinear', extent=(-4, 4, -4, 4), cmap='plasma') im.set_data(LadoMx, LadoMy, M) axs.images.append(im) axs.set_xlim(0, Mx - 1) axs.set_ylim(0, My - 1) axs.set_title('Temperatura del Flujo de Aire dentro del Colector (con K=' + str(K) + ")", fontsize=14) axs.set_xlabel('Longitud (x0.05m)') axs.set_ylabel('Ancho (x0.05m)')
def sec_show_dens(coord, depth, dens, data, axe, cmap='viridis', coord_type='lon'): """ plot data on the axe, mix between imshow and contour data reordered to plot against density instead of depth return the colorbar, so user can add a label """ depth = -np.abs(depth) # to be sure that depth is negative print(dens.shape) densSort = dens[6, :] * -1 ind = np.argsort(densSort) densSorted = (densSort[ind] + 1000) data_along_dens = data[:, ind] print(np.nanmax(densSorted)) im = NonUniformImage(axe, interpolation='nearest', \ extent=(np.nanmin(coord), np.nanmax(coord), \ np.nanmax(densSorted), np.nanmin(densSorted)), \ cmap=cmap,origin='upper') # we need to reverse order of array so everything goes increasing im.set_data(coord, densSorted, data_along_dens.T) axe.images.append(im) axe.set_xlim(np.nanmin(coord), np.nanmax(coord)) axe.set_ylim(np.nanmin(densSorted), np.nanmax(densSorted)) axe.set_ylabel('Density (kg/m3)') axe.set_xlabel(coord_type + u' ($^{\circ}$ N/E)') # adding colorbar cb = plt.colorbar(im, ax=axe, extend='both') # printing scale with positive depth axe.set_yticklabels(np.abs([int(i) for i in axe.get_yticks()])) return cb
def plot_interpolant(D,interp,x,title='figure'): buff = 100.0 fig,ax = plt.subplots() plt.gca().set_aspect('equal', adjustable='box') plt.title(title,fontsize=16) N = 200 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() points = np.zeros((len(xflat),2)) points[:,0] = xflat points[:,1] = yflat val = interp(points) val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0 square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) #help(D) im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix',extent=(minx,maxx,miny,maxy)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) p = ax.scatter(x[:,0], x[:,1], c='gray',edgecolor='none',zorder=2,s=10) cbar = plt.colorbar(im) cbar.ax.set_ylabel(title) ax.set_xlim((minx-buff,maxx+buff)) ax.set_ylim((miny-buff,maxy+buff)) #fig.colorbar(p) return fig
def _do_plot(x, y, z, fname, max_interval, reference_note=None): fig = figure(figsize=(15,7.5+7.5/2)) #fig.suptitle('Narmour') ax = fig.add_subplot(111) im = NonUniformImage(ax, interpolation=None, extent=(min(x), max(x), min(y), max(y))) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y)) def format_interval_w_ref_note(reference_note): def format_interval(i, pos=None): if int(i) != i: import ipdb;ipdb.set_trace() return Note(int(reference_note.pitch + i - max_interval-1)%12).get_pitch_name()[:-1] return format_interval def format_interval_wo_ref_note(x, pos=None): if int(x) != x: import ipdb;ipdb.set_trace() return int(x-max_interval-1) if reference_note is not None: format_interval= format_interval_w_ref_note(reference_note) else: format_interval= format_interval_wo_ref_note ax.set_xlabel('Intervalo realizado') ax.axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_interval_wo_ref_note)) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(base=1.0)) if reference_note is not None: ax.set_ylabel('Segunda nota') else: ax.set_ylabel('Intervalo implicativo') ax.axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_interval)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator()) cb = plt.colorbar(im) pylab.grid(True) pylab.savefig(fname) pylab.close()
def plot_nphist2d(ax, hist, bins, **kwargs): """Draw 2D numpy histogram as a 2D image Parameters ---------- ax : Axes Matplotlib axes on which histogram will be plotted. hist : ndarray, shape (N,M) Histogram to be plotted. bins : (ndarray, ndarray) Bind edges for the histograms. kwargs : dict, optional Additional parameters to pass directly to the matplotlib NonUniformImage function Returns ------- NonUniformImage Matplotlib NonUniformImage that depicts `hist`. """ bins_x = bins[0] bins_y = bins[1] range_x = (bins_x[0], bins_x[-1]) range_y = (bins_y[0], bins_y[-1]) im = NonUniformImage( ax, origin = 'lower', extent = range_x + range_y, **kwargs ) centers_x = (bins_x[1:] + bins_x[:-1]) / 2 centers_y = (bins_y[1:] + bins_y[:-1]) / 2 im.set_data(centers_x, centers_y, hist.T) ax.images.append(im) ax.set_xlim(range_x) ax.set_ylim(range_y) return im
def plot_img(img, filename='image.png', xlim=None, ylim=None, title="", xlabel="", ylabel=""): # if not xlim: xlim = (0, img.shape[1] - 1) if not ylim: ylim = (0, img.shape[0] - 1) x = numpy.linspace(xlim[0], xlim[1], img.shape[1]) y = numpy.linspace(ylim[0], ylim[1], img.shape[0]) # fig = plt.figure() ax = fig.add_subplot(111) im = NonUniformImage(ax, cmap=cm.Greys)#, norm=colo.LogNorm(vmin=.00001)) im.set_data(x, y, img) ax.images.append(im) # ax.set_xlim(*xlim) ax.set_ylim(*ylim) if title: ax.set_title(title) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) # plt.show() plt.savefig(filename)
def show_plot(self, x_data=(), y_data=(), z_data=(), values=(), x_label=None, y_label=None, title=None, cmap=None, interpolation="nearest"): if (len(values) > 0): assert (len(x_data) == len(y_data) == len(z_data) == 0) (x_data, y_data, z_data) = convert_xyz_value_list(values) from matplotlib.image import NonUniformImage self.figure.clear() ax = self.figure.add_subplot(111) im = NonUniformImage(ax, interpolation=interpolation) if (cmap is not None): im.set_cmap(get_colormap(cmap)) im.set_data(x_data, y_data, z_data) ax.images.append(im) ax.set_xlim(x_data[0], x_data[-1]) ax.set_ylim(y_data[0], y_data[-1]) if (x_label is not None): ax.set_xlabel(x_label) if (y_label is not None): ax.set_ylabel(y_label) if (title is not None): ax.set_title(title) self.canvas.draw()
def plot_stacked_time_series_image(self, fig, ax, x, y, z, title='', ylabel='', cbar_title='', title_font={}, axis_font={}, tick_font = {}, **kwargs): ''' This plot is a stacked time series that uses NonUniformImage with regualrly spaced ydata from a linear interpolation. Designed to support FRF ADCP data. ''' if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default # z = np.ma.array(z, mask=np.isnan(z)) h = NonUniformImage(ax, interpolation='bilinear', extent=(min(x), max(x), min(y), max(y)), cmap=plt.cm.jet) h.set_data(x, y, z) ax.images.append(h) ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y)) # h = plt.pcolormesh(x, y, z, shading='gouraud', **kwargs) # h = plt.pcolormesh(x, y, z, **kwargs) if ylabel: ax.set_ylabel(ylabel, **axis_font) if title: ax.set_title(title, **title_font) # plt.axis('tight') ax.xaxis_date() date_list = mdates.num2date(x) self.get_time_label(ax, date_list) fig.autofmt_xdate() # if invert: ax.invert_yaxis() cbar = plt.colorbar(h) if cbar_title: cbar.ax.set_ylabel(cbar_title, **axis_font) ax.grid(True) if tick_font: ax.tick_params(**tick_font)
def twoD_scalar(x, y, i0, fig, ax, **kwargs): reverse = [False, False] if "reverse_axis" in kwargs.keys(): reverse = kwargs["reverse_axis"] kwargs.pop("reverse_axis") i = int(i0 / 2) j = i0 % 2 x0 = x[0].coordinates.value x1 = x[1].coordinates.value y00 = y[i0].components[0].real.astype(np.float64) extent = [x0[0], x0[-1], x1[0], x1[-1]] if x[0].type == "linear" and x[1].type == "linear": # print('uniform') cs = ax[i][j].imshow( y00, extent=extent, origin="lower", aspect="auto", **kwargs ) else: # print('non-uniform') cs = NonUniformImage(ax[i][j], interpolation="none", extent=extent, **kwargs) cs.set_data(x0, x1, y00 / y00.max()) ax[i][j].images.append(cs) cbar = fig.colorbar(cs, ax=ax[i][j]) cbar.ax.minorticks_off() cbar.set_label(y[i0].axis_label[0]) ax[i][j].set_xlim([extent[0], extent[1]]) ax[i][j].set_ylim([extent[2], extent[3]]) ax[i][j].set_xlabel(f"{x[0].axis_label} - 0") ax[i][j].set_ylabel(f"{x[1].axis_label} - 1") ax[i][j].set_title("{0}".format(y[i0].name)) ax[i][j].grid(color="gray", linestyle="--", linewidth=0.5) if reverse[0]: ax[i][j].invert_xaxis() if reverse[1]: ax[i][j].invert_yaxis()
def plot_image(x, y, fig, ax): # if x[0].type != 'labeled': # extent = [x[0].coordinates[0].value, x[0].coordinates[-1].value, # x[1].coordinates[0].value, x[1].coordinates[-1].value] x0 = x[0].coordinates.value x1 = x[1].coordinates.value y00 = y.components[0].real.astype(np.float64).real extent = [x0[0], x0[-1], x1[1], x1[-1]] if x[0].type == "linear" and x[1].type == "linear": # print('uniform') cs = ax.imshow(y00, extent=extent, origin="lower", aspect="auto", cmap="Blues") else: # print('non-uniform') cs = NonUniformImage(ax, interpolation="nearest", extent=extent, cmap="bone_r") cs.set_data(x0, x1, y00 / y00.max()) ax.images.append(cs) # cs = ax.imshow( # y00, # extent=extent, # origin='lower', # aspect='auto', # cmap='viridis', # interpolation='none' # ) cbar = fig.colorbar(cs, ax=ax) cbar.ax.minorticks_off() cbar.set_label(y.axis_label[0]) ax.set_xlim([extent[0], extent[1]]) ax.set_ylim([extent[2], extent[3]]) ax.set_xlabel(f"{x[0].axis_label} - 0") ax.set_ylabel(f"{x[1].axis_label} - 1") ax.set_title("{0}".format(y.name)) ax.grid(color="gray", linestyle="--", linewidth=0.1)
def plot_time_frequency(spectrum, interpolation='bilinear', background_color=None, clim=None, dbscale=True, **kwargs): """ Time-frequency plot. Modeled after image_nonuniform.py example spectrum is a dataframe with frequencies in columns and time in rows """ if spectrum is None: return None times = spectrum.index freqs = spectrum.columns if dbscale: z = 10 * np.log10(spectrum.T) else: z = spectrum.T ax = plt.figure().add_subplot(111) extent = (times[0], times[-1], freqs[0], freqs[-1]) im = NonUniformImage(ax, interpolation=interpolation, extent=extent) if background_color: im.get_cmap().set_bad(kwargs['background_color']) else: z[np.isnan(z)] = 0.0 # replace missing values with 0 color if clim: im.set_clim(clim) if 'cmap' in kwargs: im.set_cmap(kwargs['cmap']) im.set_data(times, freqs, z) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.images.append(im) if 'colorbar_label' in kwargs: plt.colorbar(im, label=kwargs['colorbar_label']) else: plt.colorbar(im, label='Power (dB/Hz)') plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)') return plt.gcf()
def plot2d(x, y, z, ax=None, cmap='RdGy', norm=None, **kw): """ Plot dataset using NonUniformImage class Parameters ---------- x : (nx,) y : (ny,) z : (nx,nz) """ from matplotlib.image import NonUniformImage if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) xlim = (x.min(), x.max()) ylim = (y.min(), y.max()) im = NonUniformImage(ax, interpolation='bilinear', extent=xlim + ylim, cmap=cmap) if norm is not None: im.set_norm(norm) im.set_data(x, y, z, **kw) ax.images.append(im) #plt.colorbar(im) ax.set_xlim(xlim) ax.set_ylim(ylim) def update(z): return im.set_data(x, y, z, **kw) return im, update
def plot_probe(data, ax=None, show_cbar=True, make_pretty=True, fig_kwargs=dict(), line_kwargs=dict()): """ Function to create matplotlib plot from ProbePlot object :param data: ProbePlot object, either class or dict :param ax: matplotlib axis to plot on, if None, will create figure :param show_cbar: whether or not to display colour bar :param make_pretty: get rid of spines on axis :param fig_kwargs: dict of matplotlib keywords associcated with plt.subplots e.g can be fig size, tight layout etc. :param line_kwargs: dict of matplotlib keywords associated with ax.hlines/ax.vlines :return: matplotlib axis and figure handles """ if not isinstance(data, dict): data = data.convert2dict() if not ax: fig, ax = plt.subplots(figsize=(2, 8), **fig_kwargs) else: fig = plt.gcf() for (x, y, dat) in zip(data['data']['x'], data['data']['y'], data['data']['c']): im = NonUniformImage(ax, interpolation='nearest', cmap=data['cmap']) im.set_clim(data['clim'][0], data['clim'][1]) im.set_data(x, y, dat.T) ax.images.append(im) ax.set_xlim(data['xlim'][0], data['xlim'][1]) ax.set_ylim(data['ylim'][0], data['ylim'][1]) ax.set_xlabel(data['labels']['xlabel']) ax.set_ylabel(data['labels']['ylabel']) ax.set_title(data['labels']['title']) if make_pretty: ax.get_xaxis().set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) if show_cbar: cbar = fig.colorbar(im, orientation="horizontal", pad=0.02, ax=ax) cbar.set_label(data['labels']['clabel']) ax = add_lines(ax, data, **line_kwargs) plt.show() return ax, fig
def plot_2d_to_axis( spectrum: Spectrum2D, ax: Axes, cmap: Union[str, Colormap] = 'viridis', interpolation: str = 'nearest', norm: Optional[Normalize] = None, ) -> NonUniformImage: """Plot Spectrum2D object to Axes Parameters ---------- spectrum 2D data object for plotting as NonUniformImage. The x_tick_labels attribute will be used to mark labelled points. ax Matplotlib axes to which image will be drawn cmap Matplotlib colormap or registered colormap name interpolation Interpolation method: 'nearest' or 'bilinear' for a pixellated or smooth result norm Matplotlib normalization object; set this in order to ensure separate plots are on the same colour scale. """ x_unit = spectrum.x_data_unit y_unit = spectrum.y_data_unit z_unit = spectrum.z_data_unit x_bins = spectrum.get_bin_edges('x').to(x_unit).magnitude y_bins = spectrum.get_bin_edges('y').to(y_unit).magnitude image = NonUniformImage(ax, interpolation=interpolation, extent=(min(x_bins), max(x_bins), min(y_bins), max(y_bins)), cmap=cmap) if norm is not None: image.set_norm(norm) image.set_data( spectrum.get_bin_centres('x').to(x_unit).magnitude, spectrum.get_bin_centres('y').to(y_unit).magnitude, spectrum.z_data.to(z_unit).magnitude.T) ax.images.append(image) ax.set_xlim(min(x_bins), max(x_bins)) ax.set_ylim(min(y_bins), max(y_bins)) _set_x_tick_labels(ax, spectrum.x_tick_labels, spectrum.x_data) return image
def plotAnalysis(self, widget): Xvar = self.cbXAxis.get_active_text() Yvar = self.cbYAxis.get_active_text() Zvar = self.cbZAxis.get_active_text() if Xvar == None or Yvar == None or Zvar == None: return if Zvar == "None": XvarIndex = self.logfile.params().index(Xvar)+1 YvarIndex = self.logfile.params().index(Yvar)+1 rowiter = self.treemodelsorted.get_iter_first() values = defaultdict(list) while rowiter != None: X = self.treemodelsorted.get_value(rowiter,XvarIndex) Y = self.treemodelsorted.get_value(rowiter,YvarIndex) values[float(X)].append(float(Y)) rowiter = self.treemodelsorted.iter_next(rowiter) X = [] Y = [] for k in sorted(values.keys()): X.append(k) Y.append(mean(values[k])) self.axisAN.cla() self.figureAN.clf() self.axisAN = self.figureAN.add_subplot(111) self.axisAN.plot(X,Y, 'k', linewidth=4) self.axisAN.set_xlabel(Xvar) self.axisAN.set_ylabel(Yvar) self.canvasAN.draw() else: XvarIndex = self.logfile.params().index(Xvar)+1 YvarIndex = self.logfile.params().index(Yvar)+1 ZvarIndex = self.logfile.params().index(Zvar)+1 rowiter = self.treemodelsorted.get_iter_first() values = {} Ykeys = [] while rowiter != None: X = self.treemodelsorted.get_value(rowiter,XvarIndex) Y = self.treemodelsorted.get_value(rowiter,YvarIndex) Z = self.treemodelsorted.get_value(rowiter,ZvarIndex) Ykeys.append(Y) values.setdefault(X,defaultdict(list))[Y].append(Z) rowiter = self.treemodelsorted.iter_next(rowiter) Ykeys = unique(Ykeys) XY = [] for k in sorted(values.keys()): tmp = [] for k2 in sorted(Ykeys): if values[k].has_key(k2): tmp.append(mean(values[k][k2])) else: tmp.append(0) XY.append(tmp) Z = array(XY) self.axisAN.cla() self.figureAN.clf() self.axisAN = self.figureAN.add_subplot(111) im = NonUniformImage(self.axisAN, interpolation='nearest', extent=(min(values.keys()),max(values.keys()),min(Ykeys),max(Ykeys))) im.set_data(values.keys(), Ykeys, Z.transpose()) self.axisAN.images.append(im) self.axisAN.set_xlim(min(values.keys()),max(values.keys())) self.axisAN.set_ylim(min(Ykeys),max(Ykeys)) self.axisAN.set_xlabel(Xvar) self.axisAN.set_ylabel(Yvar) self.axisAN.set_title(Zvar) self.figureAN.colorbar(im) self.canvasAN.draw()
def go(self): '''Plot the evolution of the histogram for iterations self.iter_start to self.iter_stop''' idim = self.dimensions[0]['idim'] n_iters = self.input_h5['n_iter'][...] iiter_start = numpy.searchsorted(n_iters, self.iter_start) iiter_stop = numpy.searchsorted(n_iters, self.iter_stop) binbounds = self.input_h5['binbounds_{}'.format(idim)][...] midpoints = self.input_h5['midpoints_{}'.format(idim)][...] hists_ds = self.input_h5['histograms'] itercount = self.iter_stop - self.iter_start # We always round down, so that we don't have a dangling partial block at the end nblocks = itercount // self.iter_step block_iters = numpy.empty((nblocks, 2), dtype=n_iters.dtype) blocked_hists = numpy.zeros((nblocks, hists_ds.shape[1 + idim]), dtype=hists_ds.dtype) for iblock, istart in enumerate( xrange(iiter_start, iiter_start + nblocks * self.iter_step, self.iter_step)): istop = min(istart + self.iter_step, iiter_stop) histslice = hists_ds[istart:istop] # Sum over time histslice = numpy.add.reduce(histslice, axis=0) # Sum over other dimensions blocked_hists[iblock] = sum_except_along(histslice, idim) # Normalize normhistnd(blocked_hists[iblock], [binbounds]) block_iters[iblock, 0] = n_iters[istart] block_iters[iblock, 1] = n_iters[istop - 1] + 1 #enehists = -numpy.log(blocked_hists) enehists = self._ener_zero(blocked_hists) log10hists = numpy.log10(blocked_hists) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath( self.input_h5.filename) output_h5.attrs['source_dimension'] = idim output_h5['midpoints'] = midpoints output_h5['histograms'] = blocked_hists output_h5['n_iter'] = block_iters if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehists label = r'$\Delta F(x)\,/\,kT$' + '\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hists label = r'$\log_{10}\ P(x)$' else: plothist = blocked_hists label = r'$P(x)$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0], midpoints[-1], block_iters[0, -1], block_iters[-1, -1]), origin='lower', norm=norm) # not sure why plothist works but plothist.T doesn't, and the opposite is true # for _do_2d_output nui.set_data(midpoints, block_iters[:, -1], plothist) ax.images.append(nui) ax.set_xlim(midpoints[0], midpoints[-1]) ax.set_ylim(block_iters[0, -1], block_iters[-1, -1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel('WE Iteration') if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) pyplot.savefig(self.plot_output_filename)
def test_nonuniformimage_setnorm(): ax = plt.gca() im = NonUniformImage(ax) im.set_norm(plt.Normalize())
def cross_wavelet(self, signal_1, signal_2, mother='morlet', plot=True): signal_1 = (signal_1 - signal_1.mean()) / signal_1.std() # Normalizing signal_2 = (signal_2 - signal_2.mean()) / signal_2.std() # Normalizing W12, cross_coi, freq, signif = wavelet.xwt(signal_1, signal_2, self.period, dj=1/100, s0=-1, J=-1, significance_level=0.95, wavelet=mother, normalize=True) cross_power = np.abs(W12)**2 cross_sig = np.ones([1, signal_1.size]) * signif[:, None] cross_sig = cross_power / cross_sig cross_period = 1/freq WCT, aWCT, corr_coi, freq, sig = wavelet.wct(signal_1, signal_2, self.period, dj=1/100, s0=-1, J=-1, sig=False,significance_level=0.95, wavelet=mother, normalize=True) cor_sig = np.ones([1, signal_1.size]) * sig[:, None] cor_sig = np.abs(WCT) / cor_sig cor_period = 1/freq angle = 0.5 * np.pi - aWCT u, v = np.cos(angle), np.sin(angle) t1 = np.linspace(0,self.period*signal_1.size,signal_1.size) ## indices for stuff idx = self.find_closest(cor_period,corr_coi.max()) ## Into minutes t1 /= 60 cross_period /= 60 cor_period /= 60 cross_coi /= 60 corr_coi /= 60 fig1, ax1 = plt.subplots(nrows=1,ncols=1, sharex=True, sharey=True, figsize=(12,12)) extent_cross = [t1.min(),t1.max(),0,max(cross_period)] extent_corr = [t1.min(),t1.max(),0,max(cor_period)] im1 = NonUniformImage(ax1, interpolation='nearest', extent=extent_cross) im1.set_cmap('cubehelix') im1.set_data(t1, cross_period[:idx], cross_power[:idx,:]) ax1.images.append(im1) ax1.contour(t1, cross_period[:idx], cross_sig[:idx,:], [-99, 1], colors='k', linewidths=2, extent=extent_cross) ax1.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([cross_coi,[1e-9], cross_period[-1:], cross_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') ax1.set_title('Cross-Wavelet') # ax1.quiver(t1[::3], cross_period[::3], u[::3, ::3], # v[::3, ::3], units='width', angles='uv', pivot='mid', # linewidth=1.5, edgecolor='k', headwidth=10, headlength=10, # headaxislength=5, minshaft=2, minlength=5) ax1.set_ylim(([min(cross_period), cross_period[idx]])) ax1.set_xlim(t1.min(),t1.max()) fig2, ax2 = plt.subplots(nrows=1,ncols=1, sharex=True, sharey=True, figsize=(12,12)) fig2.subplots_adjust(right=0.8) cbar_ax_1 = fig2.add_axes([0.85, 0.05, 0.05, 0.35]) im2 = NonUniformImage(ax2, interpolation='nearest', extent=extent_corr) im2.set_cmap('cubehelix') im2.set_data(t1, cor_period[:idx], np.log10(WCT[:idx,:])) ax2.images.append(im2) ax2.contour(t1, cor_period[:idx], cor_sig[:idx,:], [-99, 1], colors='k', linewidths=2, extent=extent_corr) ax2.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([corr_coi,[1e-9], cor_period[-1:], cor_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') ax2.set_title('Cross-Correlation') # ax2.quiver(t1[::3], cor_period[::3], u[::3,::3], v[::3,::3], # units='height', angles='uv', pivot='mid',linewidth=1.5, edgecolor='k', # headwidth=10, headlength=10, headaxislength=5, minshaft=2, minlength=5) ax2.set_ylim(([min(cor_period), cor_period[idx]])) ax2.set_xlim(t1.min(),t1.max()) fig2.colorbar(im2, cax=cbar_ax_1) plt.show() plt.figure(figsize=(12,12)) im3= plt.imshow(np.rad2deg(aWCT), origin='lower',interpolation='nearest', cmap='seismic', extent=extent_corr) plt.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([corr_coi,[1e-9], cor_period[-1:], cor_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') plt.ylim(([min(cor_period), cor_period[idx]])) plt.xlim(t1.min(),t1.max()) plt.colorbar(im3) plt.show() return
# Linear x array for cell centers: x = np.linspace(-4, 4, 9) # Highly nonlinear x array: x2 = x**3 y = np.linspace(-4, 4, 9) z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2) fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True) fig.suptitle('NonUniformImage class', fontsize='large') ax = axs[0, 0] im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4), cmap=cm.Purples) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.set_title(interp) ax = axs[0, 1] im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4), cmap=cm.Purples) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64, 64)
fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(131, title='imshow: square bins') plt.imshow(H, interpolation='nearest', origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) # <matplotlib.image.AxesImage object at 0x...> # :func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges: ax = fig.add_subplot(132, title='pcolormesh: actual edges', aspect='equal') X, Y = np.meshgrid(xedges, yedges) ax.pcolormesh(X, Y, H) # <matplotlib.collections.QuadMesh object at 0x...> # :class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to # display actual bin edges with interpolation: ax = fig.add_subplot(133, title='NonUniformImage: interpolated', aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters, ycenters, H) ax.images.append(im) plt.show()
power1 = (np.abs(W1)) ** 2 # Normalized wavelet power spectrum power2 = (np.abs(W2)) ** 2 # Normalized wavelet power spectrum period1 = 1/freqs1 period2 = 1/freqs2 sig95_1 = np.ones([1, n1]) * signif1[:, None] sig95_1 = power1 / sig95_1 # Where ratio > 1, power is significant sig95_2 = np.ones([1, n2]) * signif2[:, None] sig95_2 = power2 / sig95_2 # Where ratio > 1, power is significant # First plot is of both CWT fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True) extent1 = [t1.min(), t1.max(), 0, max(period1)] extent2 = [t2.min(), t2.max(), 0, max(period2)] im1 = NonUniformImage(ax1, interpolation='bilinear', extent=extent1) im1.set_data(t1, period1, power1) ax1.images.append(im1) ax1.contour(t1, period1, sig95_1, [-99, 1], colors='k', linewidths=2, extent=extent1) ax1.fill(np.concatenate([t1, t1[-1:]+dt, t1[-1:]+dt, t1[:1]-dt, t1[:1]-dt]), np.concatenate([coi1, [1e-9], period1[-1:], period1[-1:], [1e-9]]), 'k', alpha=0.3, hatch='x') ax1.set_title('{} Wavelet Power Spectrum ({})'.format(data1['nick'], mother.name)) im2 = NonUniformImage(ax2, interpolation='bilinear', extent=extent2) im2.set_data(t2, period2, power2) ax2.images.append(im2) ax2.contour(t2, period2, sig95_2, [-99, 1], colors='k', linewidths=2, extent=extent2)
# First sub-plot, the original time series anomaly. ax = plt.axes([0.1, 0.75, 0.65, 0.2]) ax.plot(time, iwave, '-', linewidth=1, color=[0.5, 0.5, 0.5]) ax.plot(time, var, 'k', linewidth=1.5) ax.set_title('a) %s' % (title, )) if units != '': ax.set_ylabel(r'%s [$%s$]' % (label, units,)) else: ax.set_ylabel(r'%s' % (label, )) extent = [time.min(),time.max(),0,max(period)] # Second sub-plot, the normalized wavelet power spectrum and significance level # contour lines and cone of influece hatched area. bx = plt.axes([0.1, 0.37, 0.65, 0.28], sharex=ax) im = NonUniformImage(bx, interpolation='bilinear', extent=extent) im.set_data(time, period, power/scales[:, None]) bx.images.append(im) bx.contour(time, period, sig95, [-99, 1], colors='k', linewidths=2, extent=extent) bx.fill(np.concatenate([time, time[-1:]+dt, time[-1:]+dt,time[:1]-dt, time[:1]-dt]), (np.concatenate([coi,[1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') bx.set_title('b) %s Wavelet Power Spectrum (%s)' % (label, mother.name)) bx.set_ylabel('Period (years)') # Third sub-plot, the global wavelet and Fourier power spectra and theoretical # noise spectra. cx = plt.axes([0.77, 0.37, 0.2, 0.28], sharey=bx) cx.plot(glbl_signif, (period), 'k--') cx.plot(glbl_power, (period), 'k-', linewidth=1.5)
# Linear x array for cell centers: x = np.linspace(-4, 4, 9) # Highly nonlinear x array: x2 = x**3 y = np.linspace(-4, 4, 9) z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2) fig, axs = plt.subplots(nrows=2, ncols=2) fig.subplots_adjust(bottom=0.07, hspace=0.3) fig.suptitle('NonUniformImage class', fontsize='large') ax = axs[0, 0] im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4), cmap=cm.Purples) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.set_title(interp) ax = axs[0, 1] im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4), cmap=cm.Purples) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64, 64) ax.set_ylim(-4, 4) ax.set_title(interp)
def plot(self, data, fmt, xmin, xmax, ymin, ymax, zmin, zmax, **opts): """ Plot the data entry. Raises NeXusError if the data cannot be plotted. """ try: import matplotlib.pyplot as plt except ImportError: raise NeXusError("Default plotting package (matplotlib) not available.") over = opts.pop("over", False) image = opts.pop("image", False) log = opts.pop("log", False) logx = opts.pop("logx", False) logy = opts.pop("logy", False) if fmt == '': fmt = 'o' if over: plt.autoscale(enable=False) else: plt.autoscale(enable=True) plt.clf() signal = data.nxsignal axes = data.nxaxes errors = data.nxerrors title = data.nxtitle # Provide a new view of the data if there is a dimension of length 1 if 1 in signal.shape: data, axes = _fixaxes(signal, axes) else: data = signal.nxdata # Find the centers of the bins for histogrammed data axis_data = centers(data, axes) #One-dimensional Plot if len(data.shape) == 1: if hasattr(signal, 'units'): if not errors and signal.units == 'counts': errors = NXfield(np.sqrt(data)) if errors: ebars = errors.nxdata plt.errorbar(axis_data[0], data, ebars, fmt=fmt, **opts) else: plt.plot(axis_data[0], data, fmt, **opts) if not over: ax = plt.gca() xlo, xhi = ax.set_xlim(auto=True) ylo, yhi = ax.set_ylim(auto=True) if xmin: xlo = xmin if xmax: xhi = xmax ax.set_xlim(xlo, xhi) if ymin: ylo = ymin if ymax: yhi = ymax ax.set_ylim(ylo, yhi) if logx: ax.set_xscale('symlog') if log or logy: ax.set_yscale('symlog') plt.xlabel(label(axes[0])) plt.ylabel(label(signal)) plt.title(title) #Two dimensional plot else: from matplotlib.image import NonUniformImage from matplotlib.colors import LogNorm, Normalize if len(data.shape) > 2: slab = [] if image: for _dim in data.shape[:-3]: slab.append(0) slab.extend([slice(None), slice(None), slice(None)]) else: for _dim in data.shape[:-2]: slab.append(0) slab.extend([slice(None), slice(None)]) data = data[slab] if 0 in slab: print "Warning: Only the top 2D slice of the data is plotted" if image: x, y = axis_data[-2], axis_data[-3] xlabel, ylabel = label(axes[-2]), label(axes[-3]) else: x, y = axis_data[-1], axis_data[-2] xlabel, ylabel = label(axes[-1]), label(axes[-2]) if not zmin: zmin = np.nanmin(data[data>-np.inf]) if not zmax: zmax = np.nanmax(data[data<np.inf]) if not image: if log: zmin = max(zmin, 0.01) zmax = max(zmax, 0.01) opts["norm"] = LogNorm(zmin, zmax) else: opts["norm"] = Normalize(zmin, zmax) ax = plt.gca() if image: im = ax.imshow(data, **opts) ax.set_aspect('equal') else: extent = (x[0],x[-1],y[0],y[-1]) im = NonUniformImage(ax, extent=extent, **opts) im.set_data(x, y, data) im.get_cmap().set_bad('k', 1.0) ax.set_xlim(x[0], x[-1]) ax.set_ylim(y[0], y[-1]) ax.set_aspect('auto') ax.images.append(im) if not image: plt.colorbar(im) if 'origin' in opts and opts['origin'] == 'lower': image = False if xmin: ax.set_xlim(left=xmin) if xmax: ax.set_xlim(right=xmax) if ymin: if image: ax.set_ylim(top=ymin) else: ax.set_ylim(bottom=ymin) if ymax: if image: ax.set_ylim(bottom=ymax) else: ax.set_ylim(top=ymax) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.gcf().canvas.draw_idle() plt.ion() plt.show()
z_matrix = np.array([[xi * yi for xi in range(X_MIN, X_MAX, X_STEP)] for yi in range(Y_MIN, Y_MAX, Y_STEP)]) # Plot data ################# fig = plt.figure() ax = fig.add_subplot(111) #interp='nearest' # "raw" (non smooth) map interp = 'bilinear' # "smooth" map # NonUniformImage permet de définir la position des éléments de 'z_matrix' sur # les axes. # Sans NonUniformImage, une matrice 'z_matrix' de taille (sx, sy) serait # dessinée sur un repère avec un axe des abscisses allant de 0 a sx et un axe # des ordonnées allant de 0 a sy. im = NonUniformImage(ax, interpolation=interp, extent=(X_MIN, X_MAX, Y_MIN, Y_MAX), cmap=cm.binary) # im.set_data(x, y, A) # Set the grid for the pixel centers, and the pixel values. # *x* and *y* are 1-D ndarrays of lengths N and M, respectively, specifying pixel centers # *A* is an (M,N) ndarray or masked array of values to be colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA array. im.set_data(x, y, z_matrix) ax.images.append(im) ax.set_xlim(X_MIN, X_MAX) ax.set_ylim(Y_MIN, Y_MAX) fig.colorbar(im) # draw colorbar # Save file and plot ########
def wavelet(self, signal, mother='morlet', plot=True): """ Takes a 1D signal and perfroms a continous wavelet transform. Parameters ---------- time: ndarray The 1D time series for the data data: ndarray The actual 1D data mother: string The name of the family. Acceptable values are Paul, Morlet, DOG, Mexican_hat plot: bool If True, will return a plot of the result. Returns ------- Examples -------- """ sig_level = 0.95 std2 = signal.std() ** 2 signal_orig = signal[:] signal = (signal - signal.mean())/ signal.std() t1 = np.linspace(0,self.period*signal.size,signal.size) wave, scales, freqs, coi, fft, fftfreqs = wavelet.cwt(signal, self.period, wavelet=mother, dj=1/100) power = (np.abs(wave)) ** 2 period = 1/freqs # alpha, _, _ = wavelet.ar1(signal) alpha = 0.0 ## (variance=1 for the normalized SST) signif, fft_theor = wavelet.significance(1.0, self.period, scales, 0, alpha, significance_level=sig_level, wavelet=mother) sig95 = np.ones([1, signal.size]) * signif[:, None] sig95 = power / sig95 glbl_power = std2 * power.mean(axis=1) dof = signal.size - scales glbl_signif, tmp = wavelet.significance(std2, self.period, scales, 1, alpha, significance_level=sig_level, dof=dof, wavelet=mother) ## indices for stuff idx = self.find_closest(period,coi.max()) ## Into minutes t1 /= 60 period /= 60 coi /= 60 if plot: plt.figure(figsize=(12,12)) ax = plt.axes([0.1, 0.75, 0.65, 0.2]) ax.plot(t1, signal_orig-signal_orig.mean(), 'k', linewidth=1.5) extent = [t1.min(),t1.max(),0,max(period)] bx = plt.axes([0.1, 0.1, 0.65, 0.55], sharex=ax) im = NonUniformImage(bx, interpolation='nearest', extent=extent) im.set_cmap('cubehelix') im.set_data(t1, period[:idx], power[:idx,:]) bx.images.append(im) bx.contour(t1, period[:idx], sig95[:idx,:], [-99,1], colors='w', linewidths=2, extent=extent) bx.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([coi,[1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x', zorder=100) bx.set_xlim(t1.min(),t1.max()) cx = plt.axes([0.77, 0.1, 0.2, 0.55], sharey=bx) cx.plot(glbl_signif[:idx], period[:idx], 'k--') cx.plot(glbl_power[:idx], period[:idx], 'k-', linewidth=1.5) cx.set_ylim(([min(period), period[idx]])) plt.setp(cx.get_yticklabels(), visible=False) plt.show() return wave, scales, freqs, coi, power
def go(self): '''Plot the evolution of the histogram for iterations self.iter_start to self.iter_stop''' idim = self.dimensions[0]['idim'] n_iters = self.input_h5['n_iter'][...] iiter_start = numpy.searchsorted(n_iters, self.iter_start) iiter_stop = numpy.searchsorted(n_iters, self.iter_stop) binbounds = self.input_h5['binbounds_{}'.format(idim)][...] midpoints = self.input_h5['midpoints_{}'.format(idim)][...] hists_ds = self.input_h5['histograms'] itercount = self.iter_stop - self.iter_start # We always round down, so that we don't have a dangling partial block at the end nblocks = itercount // self.iter_step block_iters = numpy.empty((nblocks,2), dtype=n_iters.dtype) blocked_hists = numpy.zeros((nblocks,hists_ds.shape[1+idim]), dtype=hists_ds.dtype) for iblock, istart in enumerate(xrange(iiter_start, iiter_start+nblocks*self.iter_step, self.iter_step)): istop = min(istart+self.iter_step, iiter_stop) histslice = hists_ds[istart:istop] # Sum over time histslice = numpy.add.reduce(histslice, axis=0) # Sum over other dimensions blocked_hists[iblock] = sum_except_along(histslice, idim) # Normalize normhistnd(blocked_hists[iblock], [binbounds]) block_iters[iblock,0] = n_iters[istart] block_iters[iblock,1] = n_iters[istop-1]+1 #enehists = -numpy.log(blocked_hists) enehists = self._ener_zero(blocked_hists) log10hists = numpy.log10(blocked_hists) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath(self.input_h5.filename) output_h5.attrs['source_dimension'] = idim output_h5['midpoints'] = midpoints output_h5['histograms'] = blocked_hists output_h5['n_iter'] = block_iters if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehists label = r'$\Delta F(x)\,/\,kT$' +'\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hists label = r'$\log_{10}\ P(x)$' else: plothist = blocked_hists label = r'$P(x)$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0], midpoints[-1], block_iters[0,-1], block_iters[-1,-1]), origin='lower', norm=norm) # not sure why plothist works but plothist.T doesn't, and the opposite is true # for _do_2d_output nui.set_data(midpoints, block_iters[:,-1], plothist) ax.images.append(nui) ax.set_xlim(midpoints[0], midpoints[-1]) ax.set_ylim(block_iters[0,-1], block_iters[-1,-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel('WE Iteration') if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) pyplot.savefig(self.plot_output_filename)
plt.title('Midplane dust temperature') plt.show() # # The "heatmap" of the 2-D temperature profile # iphi = 10 # Azimuthal index at which the temperature structure is shown cmap = cm.hot zoomr = 1. # Zoom factor fig, ax = plt.subplots() x = np.log10(a.grid.x / au) y = (np.pi / 2 - a.grid.y)[::-1] xi = np.log10(a.grid.xi / au) yi = (np.pi / 2 - a.grid.yi)[::-1] z = a.dusttemp[:, ::-1, iphi, 0].T im = NonUniformImage(ax, interpolation='nearest', cmap=cmap) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim((xi[0], (xi[-1] - xi[0]) / zoomr + xi[0])) ax.set_ylim((yi[0], yi[-1])) plt.xlabel(r'$^{10}\log(r)\; [\mathrm{AU}]$') plt.ylabel(r'$\pi/2-\theta$') norm = colors.Normalize(vmin=z.min(), vmax=z.max()) cbar = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax) cbar.set_label(r'$T\;[\mathrm{K}]$') plt.title(r'Dust temperature structure at $\phi=$' + '{0:3d}'.format(int(a.grid.z[iphi] * 180 / np.pi)) + r'$^{\circ}$') # # Compute the RADIAL tau=1 surface for stellar radiation # We focus only on the small grain component here
pl.xlabel('Slope (deg)') #pl.ylabel(r'$\frac{Ntrig(<128antennas)}{Nsimulated showers(135)}$',) #pl.ylabel('Ntrig(<128antennas) / Nsimu showers(=135)',) pl.ylabel('Trigger rate') plt.legend(loc='best',fontsize=10,ncol=2) #pl.legend(bbox_to_anchor=(0., -0.3, 0.75, .102), loc=2, ncol=2, mode="expand", borderaxespad=0.,fontsize=10) if DISPLAY_2D==1: dar=(alfa2[-1]-alfa2[0])/(Dd2[-1]-Dd2[0]) *1 #7E-4 ax = plt.subplot(223) #fig1.subplots_adjust(bottom=0.07, hspace=0.3) pl.title('Trigger rate - Conservative case') pl.ylabel('Distance [km]') pl.xlabel('Slope [deg]') im = NonUniformImage(ax,interpolation='nearest', extent=(Dd2[0],Dd2[-1],alfa2[0],alfa2[-1]),cmap='jet') im.set_data(alfa,Dd,Nconfig_ew_cons) ax.images.append(im) ax.set_ylim(Dd2[0],Dd2[-1]) ax.set_xlim(alfa2[0],alfa2[-1]) im.set_clim(0,np.max(Nconfig_ew_aggr)) pl.colorbar(im) #pl.colorbar(im,orientation="horizontal") #pl.gca().set_aspect(dar,adjustable='box') ax = plt.subplot(224) #fig1.subplots_adjust(bottom=0.07, hspace=0.3) pl.title('Trigger rate - Aggressive case') pl.ylabel('Distance [km]') pl.xlabel('Slope [deg]')
def analyzeArea(rasterTransfo, resAnalysis, pLim, newRasters, cfgPath, cfgFlags): """ Compare results to reference. Compute True positive, False negative... areas. """ fname = cfgPath['pressurefileList'] dataPressure = newRasters['newRasterPressure'] scoord = rasterTransfo['s'] lcoord = rasterTransfo['l'] cellarea = rasterTransfo['rasterArea'] indRunoutPoint = rasterTransfo['indRunoutPoint'] # initialize Arrays nTopo = len(fname) TP = np.empty((nTopo)) FN = np.empty((nTopo)) FP = np.empty((nTopo)) TN = np.empty((nTopo)) # take first simulation as reference newMask = copy.deepcopy(dataPressure[0]) # prepare mask for area resAnalysis newMask[0:indRunoutPoint] = 0 newMask[np.where(np.nan_to_num(newMask) < pLim)] = 0 newMask[np.where(np.nan_to_num(newMask) >= pLim)] = 1 # comparison rasterdata with mask log.info('{: <15} {: <15} {: <15} {: <15} {: <15}'.format( 'Sim number ', 'TP ', 'FN ', 'FP ', 'TN')) # rasterinfo nStart, m_start = np.nonzero(np.nan_to_num(newMask)) nStart = min(nStart) nTot = len(scoord) for i in range(nTopo): rasterdata = dataPressure[i] """ area # true positive: reality(mask)=1, model(rasterdata)=1 # false negative: reality(mask)=1, model(rasterdata)=0 # false positive: reality(mask)=0, model(rasterdata)=1 # true negative: reality(mask)=0, model(rasterdata)=0 """ # for each pressure-file pLim is introduced (1/3/.. kPa), where the avalanche has stopped newRasterData = copy.deepcopy(rasterdata) newRasterData[0:indRunoutPoint] = 0 newRasterData[np.where(np.nan_to_num(newRasterData) < pLim)] = 0 newRasterData[np.where(np.nan_to_num(newRasterData) >= pLim)] = 1 if cfgFlags.getboolean('savePlot') and i > 0: # read paths pathResult = cfgPath['pathResult'] projectName = cfgPath['dirName'] outname = ''.join([ pathResult, os.path.sep, 'pics', os.path.sep, projectName, '_', str(i), '_compToRef', '.pdf' ]) if not os.path.exists(os.path.dirname(outname)): os.makedirs(os.path.dirname(outname)) fig = plt.figure(figsize=(figW * 2, figH), dpi=figReso) y_lim = scoord[indRunoutPoint + 20] + resAnalysis['runout'][0, 0] # for figure: referenz-simulation bei pLim=1 ax1 = plt.subplot(121) ax1.title.set_text('Reference Peak Presseure in the RunOut area') cmap = cmapPres cmap.set_under(color='w') im = NonUniformImage(ax1, extent=[ lcoord.min(), lcoord.max(), scoord.min(), scoord.max() ], cmap=cmap) im.set_clim(vmin=pLim, vmax=np.max((dataPressure[0])[nStart:nTot + 1])) im.set_data(lcoord, scoord, dataPressure[0]) ref0 = ax1.images.append(im) cbar = ax1.figure.colorbar(im, extend='both', ax=ax1, use_gridspec=True) cbar.ax.set_ylabel('peak pressure [kPa]') ax1.set_xlim([lcoord.min(), lcoord.max()]) ax1.set_ylim([scoord[indRunoutPoint - 20], y_lim]) ax1.set_xlabel(r'$l\;[m]$') ax1.set_ylabel(r'$s\;[m]$') ax2 = plt.subplot(122) ax2.title.set_text( 'Difference between current and reference in the RunOut area\n Blue = FN, Red = FP' ) colorsList = [[0, 0, 1], [1, 1, 1], [1, 0, 0]] cmap = matplotlib.colors.ListedColormap(colorsList) cmap.set_under(color='b') cmap.set_over(color='r') cmap.set_bad(color='k') im = NonUniformImage(ax2, extent=[ lcoord.min(), lcoord.max(), scoord.min(), scoord.max() ], cmap=cmap) im.set_clim(vmin=-0.000000001, vmax=0.000000001) im.set_data(lcoord, scoord, newRasterData - newMask) ref0 = ax2.images.append(im) # cbar = ax2.figure.colorbar(im, ax=ax2, extend='both', use_gridspec=True) # cbar.ax.set_ylabel('peak pressure [kPa]') ax2.set_xlim([lcoord.min(), lcoord.max()]) ax2.set_ylim([scoord[indRunoutPoint - 20], y_lim]) ax2.set_xlabel(r'$l\;[m]$') ax2.set_ylabel(r'$s\;[m]$') plt.subplots_adjust(wspace=0.3) # fig.tight_layout() # plt.show() fig.savefig(outname, transparent=True) plt.close(fig) tpInd = np.where((newMask[nStart:nTot + 1] == True) & (newRasterData[nStart:nTot + 1] == True)) fpInd = np.where((newMask[nStart:nTot + 1] == False) & (newRasterData[nStart:nTot + 1] == True)) fnInd = np.where((newMask[nStart:nTot + 1] == True) & (newRasterData[nStart:nTot + 1] == False)) tnInd = np.where((newMask[nStart:nTot + 1] == False) & (newRasterData[nStart:nTot + 1] == False)) # Teilrasterpunkte tpCount = len(tpInd[0]) fpCount = len(fpInd[0]) fnCount = len(fnInd[0]) tnCount = len(tnInd[0]) # subareas tp = sum(cellarea[tpInd[0] + nStart, tpInd[1]]) fp = sum(cellarea[fpInd[0] + nStart, fpInd[1]]) fn = sum(cellarea[fnInd[0] + nStart, fnInd[1]]) tn = sum(cellarea[tnInd[0] + nStart, tnInd[1]]) # take reference (first simulation) as normalizing area areaSum = tp + fn TP[i] = tp FN[i] = fn FP[i] = fp TN[i] = tn log.info('{: <15} {:<15.4f} {:<15.4f} {:<15.4f} {:<15.4f}'.format( *[i + 1, tp / areaSum, fn / areaSum, fp / areaSum, tn / areaSum])) resAnalysis['TP'] = TP resAnalysis['FN'] = FN resAnalysis['FP'] = FP resAnalysis['TN'] = TN return resAnalysis
def _do_2d_output(self, hist, idims, midpoints, binbounds): enehist = self._ener_zero(hist) log10hist = numpy.log10(hist) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath(self.input_h5.filename) output_h5.attrs['source_dimensions'] = numpy.array(idims, numpy.min_scalar_type(max(idims))) output_h5.attrs['source_dimension_labels'] = numpy.array([dim['label'] for dim in self.dimensions]) for idim in idims: output_h5['midpoints_{}'.format(idim)] = midpoints output_h5['histogram'] = hist if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehist label = r'$\Delta F(\vec{x})\,/\,kT$' +'\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hist label = r'$\log_{10}\ P(\vec{x})$' else: plothist = hist plothist[~numpy.isfinite(plothist)] = numpy.nan label = r'$P(\vec{x})$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() # Transpose input so that axis 0 is displayed as x and axis 1 is displayed as y # pyplot.imshow(plothist.T, interpolation='nearest', aspect='auto', # extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), # origin='lower', vmin=vmin, vmax=vmax) # The following reproduces the former calls to imshow and colorbar norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), origin='lower', norm=norm) nui.set_data(midpoints[0], midpoints[1], plothist.T) ax.images.append(nui) ax.set_xlim(midpoints[0][0], midpoints[0][-1]) ax.set_ylim(midpoints[1][0], midpoints[1][-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel(self.dimensions[1]['label']) pyplot.ylim(self.dimensions[1].get('lb'), self.dimensions[1].get('ub')) if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) if self.plot_contour: pyplot.contour(midpoints[0], midpoints[1],plothist.T) pyplot.savefig(self.plot_output_filename)
def __Plot2D(self, xa, ya, param, con, params, label, kind, fnc_x, fnc_y, fnc_z, axis_label, fnc_filt, appto, axs, **kwargs): import pylab from matplotlib.image import NonUniformImage from numpy import linspace from scipy.interpolate import splrep, splev from mpl_toolkits.mplot3d import Axes3D if len(params) > 0: cons = self.lookup.getConditions(con, _asarray(params), fnc_filt, **kwargs) else: cons = _asarray(con) for i, con in enumerate(cons): vals = self.lookup.getWhere(con) if vals <> []: if self.objects[vals[0]].data.has_key(xa) and \ self.objects[vals[0]].data.has_key(ya): if not appto: f = pylab.figure() if kind in ['imshow', 'contour', 'contourf']: axs.append(f.add_subplot(111)) else: axs.append(f.gca(projection='3d')) else: if type(appto) in [list, tuple]: axs = appto else: axs.append(appto) ax_num = i % len(axs) if self.objects[vals[0]].data.has_key(param): ma = fnc_z(self.objects[vals[0]].getData(param)) x_axis = fnc_x(self.objects[vals[0]].getData(xa)) y_axis = fnc_y(self.objects[vals[0]].getData(ya)) else: def generateMatrix(dO, xa, ya, param, kind, ma, xs, ys): # generates a matrix for the Image or contoure plot if dO.data.has_key(xa) and dO.data.has_key(ya) and \ self.header.has_key(param): ma.append(fnc_z(dO.getData(ya))) xs.append(fnc_x(dO.getData(xa))) ys.append(fnc_y(dO.getHeader(param))) ma = [] xs = [] ys = [] self.map(generateMatrix, con, xa=xa, ya=ya, param=param, kind=kind, ma=ma, xs=xs, ys=ys) x_min, x_max = max(LP_func.transpose(xs)[0]), min( LP_func.transpose(xs)[-1]) x_axis = linspace(x_min, x_max, 400) for i in xrange(len(xs)): ma[i] = splev(x_axis, splrep(xs[i], ma[i], k=3)) xs[i] = x_axis y_axis = ys if kind == 'imshow': im = NonUniformImage(axs[ax_num], interpolation='bilinear') im.set_cmap(kwargs.get('cmap', None)) im.set_data(x_axis, y_axis, ma) if kwargs.has_key('vmin'): im.set_clim(vmin=kwargs['vmin']) if kwargs.has_key('vmax'): im.set_clim(vmax=kwargs['vmax']) axs[ax_num].images.append(im) #~ xlabel( r'Wavelength [nm]' ) #~ ylabel( r'Delay [ps]' ) pylab.show() if kwargs.has_key('bar'): bar = kwargs['bar'] kwargs.pop('bar') else: bar = True if bar: axs[ax_num].get_figure().colorbar(im) axs[ax_num].set_xlim(x_axis[0], x_axis[-1]) axs[ax_num].set_ylim(y_axis[0], y_axis[-1]) pylab.draw() elif kind == 'contour': N = kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS = axs[ax_num].contour(X, Y, ma, N, **kwargs) if kwargs.has_key('labels'): labels = kwargs['labels'] kwargs.pop('labels') fmt = {} for l, s in zip(CS.levels, labels): fmt[l] = s elif kwargs.has_key('fmt'): fmt = kwargs('fmt') else: fmt = '%1.2f' if kwargs.has_key('fontsize'): fontsize = kwargs['fontsize'] else: fontsize = 12 axs[ax_num].clabel(CS, CS.levels, inline=1, fmt=fmt, fontsize=fontsize) pylab.show() axs[ax_num].set_xlim(x_axis[0], x_axis[-1]) axs[ax_num].set_ylim(y_axis[0], y_axis[-1]) pylab.draw() elif kind == 'contourf': N = kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS = axs[ax_num].contourf(X, Y, ma, N, **kwargs) axs[ax_num].get_figure().colorbar(CS) pylab.show() axs[ax_num].set_xlim(x_axis[0], x_axis[-1]) axs[ax_num].set_ylim(y_axis[0], y_axis[-1]) pylab.draw() elif kind == 'surf': X, Y = pylab.meshgrid(x_axis, y_axis) CS = axs[ax_num].plot_surface(X, Y, pylab.array(ma), **kwargs) #axs[ax_num].get_figure().colorbar(CS, shrink=0.5, aspect=5) pylab.show() #axs[ax_num].set_xlim(x_axis[0],x_axis[-1]) #axs[ax_num].set_ylim(y_axis[0],y_axis[-1]) pylab.draw() elif kind == 'contour3d': N = kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS = axs[ax_num].contourf(X, Y, ma, N, **kwargs) if kwargs.has_key('labels'): labels = kwargs['labels'] kwargs.pop('labels') fmt = {} for l, s in zip(CS.levels, labels): fmt[l] = s elif kwargs.has_key('fmt'): fmt = kwargs('fmt') else: fmt = '%1.2f' if kwargs.has_key('fontsize'): fontsize = kwargs['fontsize'] else: fontsize = 12 axs[ax_num].clabel(CS, CS.levels, inline=1, fmt=fmt, fontsize=fontsize) pylab.show() axs[ax_num].set_xlim(x_axis[0], x_axis[-1]) axs[ax_num].set_ylim(y_axis[0], y_axis[-1]) pylab.draw() lab = self.lookup.keys_to_string(con) axs[ax_num].set_title(lab) pylab.show() pylab.draw()
scatf1 = abs(fudge*2.0*velocity.value/1.064) # single bounce scatter frequency Virgo Scatter eqn 3 scatf2 = 2.0*scatf1 scatf3 = 3.0*scatf1 scatf4 = 4.0*scatf1 scatf5 = 5.0*scatf1 # print max scatter values and their times print 'max scatter f1 = ' + str(max(scatf1)) + ' Hz' tofmax = times[argmax(scatf2)] tofmaxgps = tofmax + start_time print 'time of max f2 = ' + str(tofmax) + ' s, GPS=' + str(tofmaxgps) fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(211) # Plot Spectrogram if plotspec==1: im1 = NonUniformImage(ax1, interpolation='bilinear',extent=(min(t),max(t),10,55),cmap='jet') im1.set_data(t,freq,20.0*log10(Pxx)) if witness_base=="GDS-CALIB_STRAIN": print "setting color limits for STRAIN" im1.set_clim(-1000,-800) elif witness_base=="ASC-AS_B_RF45_Q_YAW_OUT_DQ" or witness_base=="ASC-AS_B_RF36_Q_PIT_OUT_DQ" or witness_base=="ASC-AS_A_RF45_Q_PIT_OUT_DQ" or witness_base=="LSC-MICH_IN1_DQ": im1.set_clim(-200,20) elif witness_base == "OMC-LSC_SERVO_OUT_DQ": im1.set_clim(-240,-85) ax1.images.append(im1) #cbar1 = fig.colorbar(im1) #cbar1.set_clim(-120,-40) # plot fringe prediction timeseries #ax1.plot(times,scatf5, c='blue', linewidth='0.2', label='f5') ax1.plot(times,scatf4, c='purple', linewidth='0.4', label='f4')
# Plotting fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(figsize=(12, 8), nrows=2, ncols=2) ax1.plot(time / 60, data, 'k', linewidth=1.5) ax1.set_xlabel('Time (minutes)') ax1.set_ylabel('Amplitude (No Units)') ax1.set_xlim(time.min() / 60, time.max() / 60) ax2.plot(freq[0:len(time) / 2], fft_power[0:len(time) / 2]) ax2.set_xlabel('Frequency (Hertz)') ax2.set_ylabel('Power (No Units)') ax2.axis((0.0, 0.5, 0.0, 0.30000000000000004)) extent = [time.min(), time.max(), 0, max(period)] im = NonUniformImage(ax3, interpolation='nearest', extent=extent) im.set_cmap('cubehelix_r') im.set_data(t1, period[:idx], power[:idx, :]) ax3.images.append(im) ax3.set_ylabel('Period (minutes)') ax3.set_xlabel('Time (minutes)') ax3.contour(t1, period[:idx], sig95[:idx, :], [-99, 1], colors='k', linewidths=2, extent=extent) ax3.fill(np.concatenate( [t1, t1[-1:] + dt, t1[-1:] + dt, t1[:1] - dt, t1[:1] - dt]), (np.concatenate([coi, [1e-9], period[-1:], period[-1:], [1e-9]])), 'k',
def tsys_show_dynspec(out,idx=None,ampscl=None,domedian=True,frq='linear'): ''' Given "standard" output of rd_tsys_multi(), possibly calibrated using calibration.sp_apply_cal() and/or background-subtracted using calibration.sp_bg_subtract(), make a nice image plot of the dynamic spectrum. The plot can contain multiple panels if domedian is False, or plot a single spectrum representing the median of multiple antennas. Only linear frequency scale is supported at this time. ''' from matplotlib.image import NonUniformImage from matplotlib.dates import AutoDateLocator, DateFormatter from matplotlib import colors from matplotlib.pyplot import locator_params from util import Time nant, npol, nf, nt = out['tsys'].shape if idx is None: idx_ = np.arange(nt) else: idx_ = idx ut = Time(out['ut_mjd'][idx_],format='mjd') utd = (ut.mjd - int(ut[0].mjd) + 1).astype('float') good = np.where(out['fghz'] > 2.0)[0] if frq == 'linear': fghz = out['fghz'][good] else: fghz = np.log10(out['fghz'][good]) locator = AutoDateLocator(interval_multiples=True) #maxticks=7,minticks=3, tsys = out['tsys'][:,:,good,idx_] if domedian: medtsys = np.nanmedian(np.nanmedian(tsys,0),0) fig = plt.figure() fig.suptitle('EOVSA Total Power Data for '+ut[0].iso[:10],fontsize=14) # Plot X-feed ax = fig.add_subplot(211) ax.xaxis_date() ax.set_ylabel('Frequency [GHz]') ax.set_title('Median Total Power') extent=[utd[0],utd[-1],fghz[0],fghz[-1]] # extent=[ut[0],ut[-1],fghz[0],fghz[-1]] im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medtsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) #ax.xaxis.set_minor_locator(MinuteLocator(interval=10)) # Set up date formatting fmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(fmt) labels = (10**ax.get_yticks()).astype('str') for i in range(len(labels)): labels[i] = labels[i][:4] ax.set_yticklabels(labels) # Repeat for Y-feed ax = fig.add_subplot(212) ax.xaxis_date() ax.set_xlabel('Start time '+ut[0].iso[:19]+' UT') ax.set_title('Median of Y-poln') ax.set_ylabel('Frequency [GHz]') im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medytsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) # Set up date formatting ax.xaxis.set_major_formatter(fmt) ax.set_yticklabels(labels) plt.draw() plt.show()
def plot_3D( Xdata, Ydata, Zdata, colormap="RdBu_r", color_list=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, title="", xlabel="", ylabel="", zlabel="", xticks=None, yticks=None, fig=None, ax=None, is_logscale_x=False, is_logscale_y=False, is_logscale_z=False, is_disp_title=True, type_plot="stem", is_contour=False, save_path=None, is_show_fig=None, is_switch_axes=False, win_title=None, font_name="arial", font_size_title=12, font_size_label=10, font_size_legend=8, ): """Plots a 3D graph ("stem", "surf" or "pcolor") Parameters ---------- Xdata : ndarray array of x-axis values Ydata : ndarray array of y-axis values Zdata : ndarray array of z-axis values colormap : colormap object colormap prescribed by user x_min : float minimum value for the x-axis (no automated scaling in 3D) x_max : float maximum value for the x-axis (no automated scaling in 3D) y_min : float minimum value for the y-axis (no automated scaling in 3D) y_max : float maximum value for the y-axis (no automated scaling in 3D) z_min : float minimum value for the z-axis (no automated scaling in 3D) z_max : float maximum value for the z-axis (no automated scaling in 3D) title : str title of the graph xlabel : str label for the x-axis ylabel : str label for the y-axis zlabel : str label for the z-axis xticks : list list of ticks to use for the x-axis fig : Matplotlib.figure.Figure existing figure to use if None create a new one ax : Matplotlib.axes.Axes object ax on which to plot the data is_logscale_x : bool boolean indicating if the x-axis must be set in logarithmic scale is_logscale_y : bool boolean indicating if the y-axis must be set in logarithmic scale is_logscale_z : bool boolean indicating if the z-axis must be set in logarithmic scale is_disp_title : bool boolean indicating if the title must be displayed type_plot : str type of 3D graph : "stem", "surf", "pcolor" or "scatter" is_contour : bool True to show contour line if type_plot = "pcolor" save_path : str full path including folder, name and extension of the file to save if save_path is not None is_show_fig : bool True to show figure after plot is_switch_axes : bool to switch x and y axes """ # Set if figure must be shown if is_show_fig is None if is_show_fig is None: is_show_fig = True if fig is None else False # Set if figure is 3D if type_plot not in ["pcolor", "pcolormesh", "scatter"]: is_3d = True else: is_3d = False # Set figure if needed if fig is None and ax is None: (fig, ax, _, _) = init_fig(fig=None, shape="rectangle", is_3d=is_3d) if color_list is None: color_list = COLORS # Calculate z limits if z_min is None: z_min = np_min(Zdata) if z_max is None: z_max = np_max(Zdata) # Check logscale on z axis if is_logscale_z: Zdata = 10 * log10(np_abs(Zdata)) clb_format = "%0.0f" else: clb_format = "%.4g" # Switch axes if is_switch_axes: Xdata, Ydata = Ydata, Xdata if len(Xdata.shape) > 1: Xdata = Xdata.T if len(Ydata.shape) > 1: Ydata = Ydata.T if len(Zdata.shape) > 1: Zdata = Zdata.T x_min, y_min = y_min, x_min x_max, y_max = y_max, x_max xlabel, ylabel = ylabel, xlabel xticks, yticks = yticks, xticks is_logscale_x, is_logscale_y = is_logscale_y, is_logscale_x # Plot if type_plot == "stem": cmap = matplotlib.cm.get_cmap(colormap) for xi, yi, zi in zip(Xdata, Ydata, Zdata): line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)), linewidth=2.0, marker="o", markersize=3.0, markevery=(1, 1), color=cmap(0)) ax.add_line(line) ax.set_xlim3d(x_max, x_min) ax.set_ylim3d(y_min, y_max) ax.set_zlim3d(z_min, z_max) # set correct angle ax.view_init(elev=20.0, azim=45) ax.zaxis.set_rotate_label(False) ax.set_zlabel(zlabel, rotation=0) ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.zaxis.labelpad = 5 if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) # white background ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False ax.xaxis.pane.set_edgecolor("w") ax.yaxis.pane.set_edgecolor("w") ax.zaxis.pane.set_edgecolor("w") if is_logscale_z: ax.zscale("log") elif type_plot == "surf": ax.plot_surface(Xdata, Ydata, Zdata, cmap=colormap) ax.set_xlim3d(x_max, x_min) ax.set_ylim3d(y_min, y_max) ax.set_zlim3d(z_min, z_max) ax.zaxis.set_rotate_label(False) ax.set_zlabel(zlabel, rotation=0) ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.zaxis.labelpad = 5 if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) # white background ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False ax.xaxis.pane.set_edgecolor("w") ax.yaxis.pane.set_edgecolor("w") ax.zaxis.pane.set_edgecolor("w") if is_logscale_z: ax.zscale("log") elif type_plot == "pcolor": Zdata[Zdata < z_min] = z_min Zdata[Zdata > z_max] = z_max # Handle descending order axes (e.g. spectrogram of run-down in freq/rpm map) if Ydata[-1] < Ydata[0]: Ydata = Ydata[::-1] Zdata = Zdata[:, ::-1] if Xdata[-1] < Xdata[0]: Xdata = Xdata[::-1] Zdata = Zdata[::-1, :] im = NonUniformImage( ax, interpolation="bilinear", extent=(x_min, x_max, y_max, y_min), cmap=colormap, picker=10, ) im.set_data(Xdata, Ydata, Zdata.T) im.set_clim(z_min, z_max) ax.images.append(im) if is_contour: ax.contour(Xdata, Ydata, Zdata.T, colors="black", linewidths=0.8) clb = fig.colorbar(im, ax=ax, format=clb_format) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) elif type_plot == "pcolormesh": c = ax.pcolormesh(Xdata, Ydata, Zdata, cmap=colormap, shading="gouraud", antialiased=True) clb = fig.colorbar(c, ax=ax) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) elif type_plot == "scatter": c = ax.scatter( Xdata, Ydata, # s=10, c=Zdata, marker=".", cmap=colormap, vmin=z_min, vmax=z_max, picker=True, pickradius=5, ) clb = fig.colorbar(c, ax=ax) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if is_logscale_x: ax.xscale("log") if is_logscale_y: ax.yscale("log") if is_disp_title: ax.set_title(title) if is_3d: for item in ([ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] + ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()): item.set_fontsize(font_size_label) else: for item in ([ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(font_size_label) item.set_fontname(font_name) ax.title.set_fontsize(font_size_title) ax.title.set_fontname(font_name) if save_path is not None: save_path = save_path.replace("\\", "/") fig.savefig(save_path) plt.close() if is_show_fig: fig.show() if win_title: manager = plt.get_current_fig_manager() if manager is not None: manager.set_window_title(win_title)
def test_nonuniformimage_setcmap(): ax = plt.gca() im = NonUniformImage(ax) im.set_cmap('Blues')
def tsys_show_dynspec(out, idx=None, ampscl=None, domedian=True, frq='linear'): ''' Given "standard" output of rd_tsys_multi(), possibly calibrated using calibration.sp_apply_cal() and/or background-subtracted using calibration.sp_bg_subtract(), make a nice image plot of the dynamic spectrum. The plot can contain multiple panels if domedian is False, or plot a single spectrum representing the median of multiple antennas. Only linear frequency scale is supported at this time. ''' from matplotlib.image import NonUniformImage from matplotlib.dates import AutoDateLocator, DateFormatter from matplotlib import colors from matplotlib.pyplot import locator_params from util import Time nant, npol, nf, nt = out['tsys'].shape if idx is None: idx_ = np.arange(nt) else: idx_ = idx ut = Time(out['ut_mjd'][idx_], format='mjd') utd = (ut.mjd - int(ut[0].mjd) + 1).astype('float') good = np.where(out['fghz'] > 2.0)[0] if frq == 'linear': fghz = out['fghz'][good] else: fghz = np.log10(out['fghz'][good]) locator = AutoDateLocator(interval_multiples=True) #maxticks=7,minticks=3, tsys = out['tsys'][:, :, good, idx_] if domedian: medtsys = np.nanmedian(np.nanmedian(tsys, 0), 0) fig = plt.figure() fig.suptitle('EOVSA Total Power Data for ' + ut[0].iso[:10], fontsize=14) # Plot X-feed ax = fig.add_subplot(211) ax.xaxis_date() ax.set_ylabel('Frequency [GHz]') ax.set_title('Median Total Power') extent = [utd[0], utd[-1], fghz[0], fghz[-1]] # extent=[ut[0],ut[-1],fghz[0],fghz[-1]] im = NonUniformImage(ax, extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0], vmax=ampscl[1])) im.set_data(utd, fghz, medtsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.xaxis.set_major_locator(locator) #ax.xaxis.set_minor_locator(MinuteLocator(interval=10)) # Set up date formatting fmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(fmt) labels = (10**ax.get_yticks()).astype('str') for i in range(len(labels)): labels[i] = labels[i][:4] ax.set_yticklabels(labels) # Repeat for Y-feed ax = fig.add_subplot(212) ax.xaxis_date() ax.set_xlabel('Start time ' + ut[0].iso[:19] + ' UT') ax.set_title('Median of Y-poln') ax.set_ylabel('Frequency [GHz]') im = NonUniformImage(ax, extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0], vmax=ampscl[1])) im.set_data(utd, fghz, medytsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.xaxis.set_major_locator(locator) # Set up date formatting ax.xaxis.set_major_formatter(fmt) ax.set_yticklabels(labels) plt.draw() plt.show()
def _do_2d_output(self, hist, idims, midpoints, binbounds): enehist = self._ener_zero(hist) log10hist = numpy.log10(hist) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath( self.input_h5.filename) output_h5.attrs['source_dimensions'] = numpy.array( idims, numpy.min_scalar_type(max(idims))) output_h5.attrs['source_dimension_labels'] = numpy.array( [dim['label'] for dim in self.dimensions]) for idim in idims: output_h5['midpoints_{}'.format(idim)] = midpoints output_h5['histogram'] = hist if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehist label = r'$\Delta F(\vec{x})\,/\,kT$' + '\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hist label = r'$\log_{10}\ P(\vec{x})$' else: plothist = hist plothist[~numpy.isfinite(plothist)] = numpy.nan label = r'$P(\vec{x})$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() # Transpose input so that axis 0 is displayed as x and axis 1 is displayed as y # pyplot.imshow(plothist.T, interpolation='nearest', aspect='auto', # extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), # origin='lower', vmin=vmin, vmax=vmax) # The following reproduces the former calls to imshow and colorbar norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), origin='lower', norm=norm) nui.set_data(midpoints[0], midpoints[1], plothist.T) ax.images.append(nui) ax.set_xlim(midpoints[0][0], midpoints[0][-1]) ax.set_ylim(midpoints[1][0], midpoints[1][-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel(self.dimensions[1]['label']) pyplot.ylim(self.dimensions[1].get('lb'), self.dimensions[1].get('ub')) if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) if self.plot_contour: pyplot.contour(midpoints[0], midpoints[1], plothist.T) pyplot.savefig(self.plot_output_filename)
for i in range(len(var)): var[i] = np.ma.masked_where(var[i] <= 1.0e-30, var[i]) if output_var == "beta": mag_press = (bx * bx + by * by) / (8.0 * np.pi) for i in range(len(var)): var[i] = var[i] / (mag_press**2) var[i] = mag_press * var[i] fig, ax = plt.subplots() frame = 0 x = X[:, 0] y = Y[0, :] if output_var == "rad" or output_var == "beta": im = NonUniformImage(ax, animated=True, origin='lower', extent=(x_min,x_max,y_min,y_max),\ interpolation='nearest', norm=matplotlib.colors.SymLogNorm(linthresh=1e-5, base=10)) im.set_data(x, y, np.transpose(var[frame])) im.set_clim(vmin=1e-4) ax.add_image(im) ax.set(xlim=(x_min, x_max), ylim=(y_min, y_max), xlabel="x (cm)", ylabel="y (cm)", title=output_var + ", t=" + str(t[frame])) var_colorbar = fig.colorbar(im) var_colorbar.set_label(fullnames[output_var] + " (" + fullunits[output_var] + ")") elif output_var == "dt" or output_var == "dt_thermal" or output_var == "dt_rad": im = NonUniformImage(ax, animated=True, origin='lower', extent=(x_min,x_max,y_min,y_max),\ interpolation='nearest', norm=matplotlib.colors.SymLogNorm(linthresh=1e-10, base=10)) im.set_data(x, y, np.transpose(var[frame]))
def plot(self): plt.clf() ax = self.figure.add_subplot(111) slice_str = '[?]' # extension = [] if self.view == 'X-Y': image = self.data[:,:,self.slider.value()] slice_str = 'z = %f ' % self.b.z[self.slider.value()] ax.set_ylabel('y-direction') ax.set_xlabel('x-direction') # extension = [0, self.param['mx'], 0, self.param['my']] elif self.view == 'X-Z': image = self.data[:,self.slider.value(),:] slice_str = 'y = %f ' % self.b.y[self.slider.value()] ax.set_ylabel('z-direction') ax.set_xlabel('x-direction') # extension = [0, self.param['mx'], 0, self.param['mz']] elif self.view == 'Y-Z': image = self.data[self.slider.value(),:,:] slice_str = 'x = %f ' % self.b.x[self.slider.value()] ax.set_ylabel('z-direction') ax.set_xlabel('y-direction') # extension = [0, self.param['my'], 0, self.param['mz']] # image = np.fliplr(image) # image = np.rot90(image,k=3) label = "Value" color = cm.get_cmap('jet') ax.set_title("[%s] %s (Snap: %s) for %s \n[time: %s]" % (self.tag, self.base_name, self.snap_n, slice_str, str(datetime.timedelta(seconds=self.param['t']*self.param['u_t'])))) # ax.xaxis.set_major_locator(ticker.MultipleLocator(int(64))) # ax.yaxis.set_major_locator(ticker.MultipleLocator(int(64))) if self.check_si.isChecked(): if self.tag == 'r': image = image * self.param['u_r'] unit_label = "[g/cm3]" label = "Value %s" % unit_label elif (self.tag == 'bx' or self.tag == 'by' or self.tag == 'bz'): image = image * self.param['u_b'] unit_label = "[G]" label = "Value %s" % unit_label elif (self.tag == 'px' or self.tag == 'py' or self.tag == 'pz'): image = image * self.param['u_p'] unit_label = "[Ba]" label = "Value %s" % unit_label elif self.tag == 'e': image = image * self.param['u_e'] unit_label = "[erg]" label = "Value %s" % unit_label if self.check_abs.isChecked(): image = np.absolute(image) label = "ABS( %s )" % label if self.check_log.isChecked(): image = np.log10(image) label = "Log10( %s )" % label if self.check_bw.isChecked(): # color = cm.get_cmap('gist_yarg') color = cm.get_cmap('Greys_r') # Mats favorite color palette if self.view == 'X-Y': ax.set_ylabel('y-direction [Mm]') ax.set_xlabel('x-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.x.min(),self.b.x.max(),self.b.y.min(),self.b.y.max()), cmap=color) im.set_data(self.b.x, self.b.y, np.fliplr(zip(*image[::-1]))) ax.images.append(im) ax.set_xlim(self.b.x.min(),self.b.x.max()) ax.set_ylim(self.b.y.min(),self.b.y.max()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(4))) elif self.view == 'X-Z': ax.set_ylabel('z-direction [Mm]') ax.set_xlabel('x-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.x.min(),self.b.x.max(),self.b.z.min(),self.b.z.max()), cmap=color) im.set_data(self.b.x, self.b.z[::-1], np.flipud(np.fliplr(zip(*image[::-1])))) ax.images.append(im) ax.set_xlim(self.b.x.min(),self.b.x.max()) ax.set_ylim(self.b.z.max(),self.b.z.min()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(2))) elif self.view == 'Y-Z': ax.set_ylabel('z-direction [Mm]') ax.set_xlabel('y-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.y.min(),self.b.y.max(),self.b.z.min(),self.b.z.max()), cmap=color) im.set_data(self.b.y, self.b.z[::-1], np.flipud(np.fliplr(zip(*image[::-1])))) ax.images.append(im) ax.set_xlim(self.b.y.min(),self.b.y.max()) ax.set_ylim(self.b.z.max(),self.b.z.min()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(2))) # im = ax.imshow(image, interpolation='none', origin='lower', cmap=color, extent=extension) # ax.text(0.025, 0.025, (r'$\langle B_{z} \rangle = %2.2e$'+'\n'+r'$\langle |B_{z}| \rangle = %2.2e$') % (np.average(img),np.average(np.absolute(img))), ha='left', va='bottom', transform=ax.transAxes) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax,label=label) self.canvas.draw()
def imshow_field(field, grid=None, ax=None, vmin=None, vmax=None, aspect='equal', norm=None, interpolation=None, non_linear_axes=False, cmap=None, mask=None, mask_color='k', *args, **kwargs): '''Display a two-dimensional image on a matplotlib figure. This function serves as an easy replacement for the matplotlib.pyplot.imshow() function. Its signature mostly folows that of matplotlib, with a few minor differences. Parameters ---------- field : Field or ndarray The field that we want to display. If this is an ndarray, then the parameter `grid` needs to be supplied. If the field is complex, then it will be automatically fed into :func:`complex_field_to_rgb`. If the field is a vector field with length 3 or 4, these will be interpreted as an RGB or RGBA field. grid : Grid or None If a grid is supplied, it will be used instead of the grid of `field`. ax : matplotlib axes The axes which to draw on. If it is not given, the current axes will be used. vmin : scalar The minimum value on the colorbar. If it is not given, then the minimum value of the field will be used. vmax : scalar The maximum value on the colorbar. If it is not given, then the maximum value of the field will be used. aspect : ['auto', 'equal', scalar] If 'auto', changes the image aspect ratio to match that of the axes. If 'equal', changes the axes aspect ratio to match that of the image. norm : Normalize A Normalize instance is used to scale the input to the (0, 1) range for input to the `cmap`. If it is not given, a linear scale will be used. interpolation : string The interpolation method used. The default is 'nearest'. Supported values are {'nearest', 'bilinear'}. non_linear_axes : boolean If axes are scaled in a non-linear way, for example on a log plot, then imshow_field needs to use a more expensive implementation. This parameter is to indicate that this algorithm needs to be used. cmap : Colormap The colormap with which to plot the image. It is ignored if a complex field or a vector field is supplied. mask : field or ndarray If part of the image needs to be masked, this mask is overlayed on top of the image. This is for example useful when plotting a phase pattern on a certain aperture, which has no meaning outside of the aperture. Masks can be partially translucent, and will be automatically scaled between (0, 1). Zero means invisible, one means visible. mask_color : Color The color of the mask, if it is used. Returns ------- AxesImage The produced image. ''' import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.image import NonUniformImage if ax is None: ax = plt.gca() ax.set_aspect(aspect) if grid is None: grid = field.grid else: field = Field(field, grid) # If field is complex, draw complex if np.iscomplexobj(field): f = complex_field_to_rgb(field, rmin=vmin, rmax=vmax, norm=norm) vmin = None vmax = None norm = None else: f = field # Automatically determine vmin, vmax, norm if not overridden if norm is None and not np.iscomplexobj(field): if vmin is None: vmin = np.nanmin(f) if vmax is None: vmax = np.nanmax(f) norm = mpl.colors.Normalize(vmin, vmax) # Get extent c_grid = grid.as_('cartesian') min_x, min_y, max_x, max_y = c_grid.x.min(), c_grid.y.min(), c_grid.x.max( ), c_grid.y.max() if grid.is_separated and grid.is_('cartesian'): # We can draw this directly x, y = grid.coords.separated_coords z = f.shaped if np.iscomplexobj(field) or field.tensor_order > 0: z = np.rollaxis(z, 0, z.ndim) else: # We can't draw this directly. raise NotImplementedError() if non_linear_axes: # Use pcolormesh to display x_mid = (x[1:] + x[:-1]) / 2 y_mid = (y[1:] + y[:-1]) / 2 x2 = np.concatenate( ([1.5 * x[0] - 0.5 * x[1]], x_mid, [1.5 * x[-1] - 0.5 * x[-2]])) y2 = np.concatenate( ([1.5 * y[0] - 0.5 * y[1]], y_mid, [1.5 * y[-1] - 0.5 * y[-2]])) X, Y = np.meshgrid(x2, y2) im = ax.pcolormesh(X, Y, z, *args, norm=norm, rasterized=True, cmap=cmap, **kwargs) else: # Use NonUniformImage to display im = NonUniformImage(ax, extent=(min_x, max_x, min_y, max_y), interpolation=interpolation, norm=norm, cmap=cmap, *args, **kwargs) im.set_data(x, y, z) from matplotlib.patches import Rectangle patch = Rectangle((min_x, min_y), max_x - min_x, max_y - min_y, facecolor='none') ax.add_patch(patch) im.set_clip_path(patch) ax.images.append(im) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) if mask is not None: one = np.ones(grid.size) col = mpl.colors.to_rgb(mask_color) m = np.array([ one * col[0], one * col[1], one * col[2], 1 - mask / np.nanmax(mask) ]) imshow_field(m, grid, ax=ax) num_rows, num_cols = field.grid.shape def format_coord(x, y): col = int(np.round((x - min_x) / (max_x - min_x) * (num_cols - 1))) row = int(np.round((y - min_y) / (max_y - min_y) * (num_rows - 1))) if col >= 0 and col < num_cols and row >= 0 and row < num_rows: z = field.shaped[row, col] if np.iscomplexobj(z): return 'x=%0.3g, y=%0.3g, z=%0.3g + 1j * %0.3g = %0.3g * exp(1j * %0.2f)' % ( x, y, z.real, z.imag, np.abs(z), np.angle(z)) else: return 'x=%0.3g, y=%0.3g, z=%0.3g' % (x, y, z) return 'x=%0.3g, y=%0.3g' % (x, y) ax.format_coord = format_coord ax._sci(im) return im
def single_plot(data, x, y, axes=None, beta=None, cbar_label='', cmap=plt.get_cmap('RdBu'), vmin=None, vmax=None, phase_speeds=True, manual_locations=False, **kwargs): """ Plot a single frame Time-Distance Diagram on physical axes. This function uses mpl NonUniformImage to plot a image using x and y arrays, it will also optionally over plot in contours beta lines. Parameters ---------- data: np.ndarray The 2D image to plot x: np.ndarray The x coordinates y: np.ndarray The y coordinates axes: matplotlib axes instance [*optional*] The axes to plot the data on, if None, use plt.gca(). beta: np.ndarray [*optional*] The array to contour over the top, default to none. cbar_label: string [*optional*] The title label for the colour bar, default to none. cmap: A matplotlib colour map instance [*optional*] The colourmap to use, default to 'RdBu' vmin: float [*optional*] The min scaling for the image, default to the image limits. vmax: float [*optional*] The max scaling for the image, default to the image limits. phase_speeds : bool Add phase speed lines to the plot manual_locations : bool Array for clabel locations. Returns ------- None """ if axes is None: axes = plt.gca() x = x[:xxlim] data = data[:,:xxlim] im = NonUniformImage(axes,interpolation='nearest', extent=[x.min(),x.max(),y.min(),y.max()],rasterized=False) im.set_cmap(cmap) if vmin is None and vmax is None: lim = np.max([np.nanmax(data), np.abs(np.nanmin(data))]) im.set_clim(vmax=lim,vmin=-lim) else: im.set_clim(vmax=vmax,vmin=vmin) im.set_data(x,y,data) im.set_interpolation('nearest') axes.images.append(im) axes.set_xlim(x.min(),x.max()) axes.set_ylim(y.min(),y.max()) cax0 = make_axes_locatable(axes).append_axes("right", size="5%", pad=0.05) cbar0 = plt.colorbar(im, cax=cax0, ticks=mpl.ticker.MaxNLocator(7)) cbar0.set_label(cbar_label) cbar0.solids.set_edgecolor("face") kwergs = {'levels': [1., 1/3., 1/5., 1/10., 1/20.]} kwergs.update(kwargs) if beta is not None: ct = axes.contour(x,y,beta[:,:xxlim],colors=['k'], **kwergs) plt.clabel(ct,fontsize=14,inline_spacing=3, manual=manual_locations, fmt=mpl.ticker.FuncFormatter(betaswap)) axes.set_xlabel("Time [s]") axes.set_ylabel("Height [Mm]")