• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python image.NonUniformImage类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.image.NonUniformImage的典型用法代码示例。如果您正苦于以下问题:Python NonUniformImage类的具体用法?Python NonUniformImage怎么用?Python NonUniformImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了NonUniformImage类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: plot_spectrogram

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()
开发者ID:dongying,项目名称:dear,代码行数:25,代码来源:spectrogram.py


示例2: plot_spectrogram

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()
开发者ID:creasyw,项目名称:humming,代码行数:31,代码来源:spectrum.py


示例3: _update3

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
开发者ID:treverhines,项目名称:SeisRBF,代码行数:31,代码来源:plot.py


示例4: plotDensity

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)
开发者ID:pbenner,项目名称:adaptive-sampling,代码行数:7,代码来源:visualization.py


示例5: _do_plot2

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()
开发者ID:johndpope,项目名称:automusica,代码行数:29,代码来源:plot.py


示例6: test_nonuniformimage_setdata

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'
开发者ID:4over7,项目名称:matplotlib,代码行数:9,代码来源:test_image.py


示例7: plot_interpolant

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
开发者ID:treverhines,项目名称:SeisRBF,代码行数:48,代码来源:PlotSeisRBF.py


示例8: plot_interpolant

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
开发者ID:treverhines,项目名称:SeisRBF,代码行数:44,代码来源:plot.py


示例9: _do_plot

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()
开发者ID:johndpope,项目名称:automusica,代码行数:43,代码来源:plot.py


示例10: execute

 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()
开发者ID:gclos,项目名称:pyphant1,代码行数:47,代码来源:ImageVisualizer.py


示例11: plot_img

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)
开发者ID:creasyw,项目名称:humming,代码行数:21,代码来源:figure.py


示例12: plot_stacked_time_series_image

    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)
开发者ID:Bobfrat,项目名称:ooi-ui-services,代码行数:40,代码来源:plot_tools.py


示例13: plot_time_frequency

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() 
开发者ID:jmxpearson,项目名称:physutils,代码行数:42,代码来源:tf.py


示例14: plot2d

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
开发者ID:nbren12,项目名称:gnl,代码行数:36,代码来源:plots.py


示例15: abs

	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')
开发者ID:andrew-lundgren,项目名称:ligo-detchar,代码行数:31,代码来源:scatMon3.py


示例16: NonUniformImage

# 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)
开发者ID:nabobalis,项目名称:pycwt,代码行数:30,代码来源:sample.py


示例17: NonUniformImage

# 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)
开发者ID:4over7,项目名称:matplotlib,代码行数:30,代码来源:image_nonuniform.py


示例18: _do_2d_output

    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)
开发者ID:ASinanSaglam,项目名称:west_tools,代码行数:61,代码来源:plothist.py


示例19: plot

    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()
开发者ID:M1kol4j,项目名称:BQ_t4_Look,代码行数:99,代码来源:bq_t4_look.py


示例20: single_plot

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]")
开发者ID:Cadair,项目名称:VivaTalk,代码行数:74,代码来源:td_plotting_helpers.py



注:本文中的matplotlib.image.NonUniformImage类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python lines.Line2D类代码示例发布时间:2022-05-27
下一篇:
Python image.BboxImage类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap