Python matplotlib.cm.gray() Examples

The following are code examples for showing how to use matplotlib.cm.gray(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ble5-nrf52-mac   Author: tomasero   File: test_png.py    MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 2
Project: Deep_Inside_Convolutional_Networks   Author: artvandelay   File: backprop_analysis.py    MIT License 6 votes vote down vote up
def vis_square(data, padsize=1, padval=0):
    data -= data.min()
    data /= data.max()
    
    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
    
    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    
    plt.imshow(data,cmap=cm.gray)



#Perform a forward pass with the data as the input image 
Example 3
Project: neural-network-animation   Author: miloharper   File: test_png.py    MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = glob.glob(os.path.join(dirname, 'basn*.png'))
    files.sort()

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 4
Project: python3_ios   Author: holzschu   File: test_png.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 5
Project: masb2d   Author: Ylannl   File: readwrite.py    GNU General Public License v3.0 6 votes vote down vote up
def write_lfs(datadict, max_lfs=2):
    with open('lfs_out.off', 'w') as f:
        f.write("COFF\n")
        # max_lfs = nanmax(datadict['lfs'])
        m,n = datadict['coords'].shape
        f.write("{} 0 0\n".format(m))

        for p, lfs in zip(datadict['coords'], datadict['lfs']):
            if not isnan(lfs):
                red=green=blue=0
                colorval = 255-int(255 * (lfs/max_lfs))
                if colorval > 255: colorval = 255
                if colorval < 0: colorval = 0

                rgba = cm.gray([colorval])[0]

                f.write("{0} {1} {2} {3} {4} {5} {6}\n".format(p[0], p[1], p[2], int(rgba[0]*255),int(rgba[1]*255),int(rgba[2]*255),int(rgba[3]*255))) 
Example 6
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_png.py    MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 7
Project: scipy2015-3d_printing   Author: joferkington   File: make_base.py    MIT License 6 votes vote down vote up
def main():
    vol, top = load_data()
    downsample = 3

    fig = mlab.figure(bgcolor=(1,1,1))

    x, y, z = hor2xyz(top, vol, downsample)
    build_sides(vol, x, y, z, vol.nz)

    # Build top
    seafloor = top_texture(top, vol)
    top_mesh = mlab.mesh(x, y, z)
    texture(top_mesh, np.flipud(seafloor.T), cm.gray)

    build_base(x, y, z, vol)
    utils.present(fig) 
Example 8
Project: scipy2015-3d_printing   Author: joferkington   File: make_top.py    MIT License 6 votes vote down vote up
def main():
    vol, coh, base, top = load_data()
    downsample = 3
    _, _, zbase = hor2xyz(base, vol, downsample)
    x, y, ztop = hor2xyz(top, vol, downsample)

    fig = mlab.figure(bgcolor=(1,1,1))

    build_sides(vol, x, y, ztop, zbase.min(), zbase)

    # Build Base
    base_mesh = mlab.mesh(x, y, zbase)
    chan = bottom_texture(base, vol)
    texture(base_mesh, np.flipud(chan.T), cm.gray)

    # Build top
    x, y, ztop = hor2xyz(top, vol, downsample)
    seafloor = top_texture(top, coh)
    top_mesh = mlab.mesh(x, y, ztop)
    texture(top_mesh, np.flipud(seafloor.T), cm.gray)

    utils.present(fig) 
Example 9
Project: deep_intent   Author: AutonomyLab   File: plot_heatmap.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_heatmap(attn_layer, epoch, vid_num, file):
    print (attn_layer)
    for i in attn_layer:
        gen = i
        gen_name = 'gen' + str(gen)
        data = np.load(file)
        if file == "None":
            data = np.load('./../zhora/history/attention_weights_' + gen_name + '_' + str(epoch) + '.npy')
        data = data[vid_num]
        for i in range(data.shape[0]):
            for j in range(data.shape[-1]):
                frame = data[i, :, :, j]
                # frame_1 = data[i, : ,:, 0]
                print (frame.shape)
                frame = np.reshape(frame, data.shape[1:3])

                plt.clf()
                plt.imshow(frame, cmap='binary', interpolation='nearest')
                # plt.imshow(frame, cmap=cm.gray, interpolation='nearest')
                # plt.colorbar()
                # plt.cbar_axes[1].colorbar()
                plt.axis('off')
                plt.savefig(os.path.join(TEST_RESULTS_DIR, 'plot_' + gen_name + '_' + str(i) + '_' + str(j) + '.png'),
                            transparent=True) 
Example 10
Project: deep_intent   Author: AutonomyLab   File: plot_results.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_heatmap(attn_layer, epoch, vid_num, file):
    print (attn_layer)
    for i in attn_layer:
        gen = i
        gen_name = 'gen' + str(gen)
        data = np.load(file)
        if file == "None":
            data = np.load('./../zhora/history/attention_weights_' + gen_name + '_' + str(epoch) + '.npy')
        data = data[vid_num]
        for i in range(data.shape[0]):
            for j in range(data.shape[-1]):
                frame = data[i, :, :, j]
                # frame_1 = data[i, : ,:, 0]
                print (frame.shape)
                frame = np.reshape(frame, data.shape[1:3])

                plt.clf()
                plt.imshow(frame, cmap='binary', interpolation='nearest')
                # plt.imshow(frame, cmap=cm.gray, interpolation='nearest')
                # plt.colorbar()
                # plt.cbar_axes[1].colorbar()
                plt.axis('off')
                plt.savefig(os.path.join(TEST_RESULTS_DIR, 'plot_' + gen_name + '_' + str(i) + '_' + str(j) + '.png'),
                            transparent=True) 
Example 11
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_png.py    MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 12
Project: Blackjack-Tracker   Author: martinabeleda   File: test_png.py    MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 13
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_png.py    GNU General Public License v3.0 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example 14
Project: ocrd_keraslm   Author: OCR-D   File: rating.py    Apache License 2.0 6 votes vote down vote up
def plot_char_embeddings_similarity(self, filename):
        '''Paint a heat map of character embeddings.
        
        Calculate the autocorrelation matrix of embedding vectors,
        and plot it as PNG with grayscale colors into `filename`.
        
        (Similar characters should have a higher correlation and
        therefore form groups. Rare or unseen characters will be
        darker and appear random.)
        '''
        logging.getLogger('matplotlib').setLevel(logging.WARNING) # workaround
        from matplotlib import pyplot as plt
        from matplotlib import cm
        
        assert self.status == 2
        charlay = self.model.get_layer(name='char_embedding')
        charwgt = charlay.get_weights()[0]
        charcor = np.dot(charwgt, charwgt.T) # confusion matrix
        plt.imsave(filename, np.abs(charcor), cmap=cm.gray) 
Example 15
Project: ocrd_keraslm   Author: OCR-D   File: rating.py    Apache License 2.0 6 votes vote down vote up
def plot_context_embeddings_similarity(self, filename, n=1):
        '''Paint a heat map of context embeddings.
        
        Calculate the autocorrelation matrix of embedding vectors,
        and plot it as PNG with grayscale colors into `filename`.
        
        (Similar contexts should have a higher correlation and
        therefore form groups. Rare or unseen contexts will be
        darker and appear random.)
        '''
        logging.getLogger('matplotlib').setLevel(logging.WARNING) # workaround
        from matplotlib import pyplot as plt
        from matplotlib import cm
        
        assert self.status == 2
        ctxtlay = self.model.get_layer(name='context%d_embedding' % n)
        ctxtwgt = ctxtlay.get_weights()[0]
        ctxtcor = np.dot(ctxtwgt, ctxtwgt.T) # confusion matrix
        plt.imsave(filename, np.abs(ctxtcor), cmap=cm.gray) 
Example 16
Project: dasp   Author: agb32   File: mypylab.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def randomise(w,data=None):
    print "Randomising"
    X[:]=numpy.random.random((20,20)).astype("f")
    #ax = fig.add_subplot(111)
    #print dir(ax),ax.figBottom
    #dr=dir(ax)
    #for d in dr:
    #    print d,"       ",getattr(ax,d)
    ax.clear()
    ax.imshow(X,interpolation="nearest",cmap=colour.gray)
    
    #ax.redraw_in_frame()
    ax.draw()
    #event = gtk.gdk.Event(gtk.gdk.EXPOSE)
    #print dir(event),dir(event.area),type(event.area),type(event.area.x),event.area.x,event.area.height
    #event.time = -1 # assign current time
    #canvas.emit("expose_event",event)
    #self.window.draw_drawable (self.style.fg_gc[self.state],self._pixmap, 0, 0, 0, 0, w, h)
    canvas.queue_draw()
    return True 
Example 17
Project: pyCEST   Author: pganssle   File: gui.py    MIT License 5 votes vote down vote up
def load_bruker(canvas, dataPath):
    field = float(nylib.BrukerPar(dataPath, 'acqp', 'BF1='))

    data = nylib.Paravision2dseqNew(dataPath)
    freq = nylib.BrukerPar(dataPath, 'method', 'MT_Offsets_NoM0=') / field

    ax = canvas.axes

    ax.imshow(data[0, :, :], cmap=cm.gray)
    ROIH = roi.ROIHandler(ax)
    ROIH.connect()

    canvas.draw() 
Example 18
Project: pyOpenAireTextClassifier   Author: tyiannak   File: textFeatureExtraction.py    Apache License 2.0 5 votes vote down vote up
def drawGraphFromSM2(SM, names, outFile, Cut):
	graph = pydot.Dot(graph_type='graph')

	# THRESHOLD SM:
	nonZeroMean = np.mean(SM[SM.nonzero()])
	if Cut:
		T = 5.0 * nonZeroMean
	else:
		T = 0.0;

	for i in range(SM.shape[0]):
		for j in range(SM.shape[0]):
			if SM[i,j] <= T:
				SM[i,j] = 0.0
			else:
				SM[i,j] = 1.0

	numOfConnections = sum(SM, axis = 0)
	#fig = plt.figure(1)
	#plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
	#plt.show()

	numOfConnections = 9*numOfConnections / max(numOfConnections)

	for i,f in enumerate(names):	
		if sum(SM[i,:])>0:
			fillColorCurrent = "{0:d}".format(int(ceil(numOfConnections[i])))
			# NOTE: SEE http://www.graphviz.org/doc/info/colors.html for color schemes
			node = pydot.Node(f, style="filled", fontsize="8", shape="egg", fillcolor=fillColorCurrent, colorscheme = "reds9")
			graph.add_node(node)
			
	for i in range(len(names)):
		for j in range(len(names)):
			if i<j:
				if SM[i][j] > 0:
					#gr.add_edge((names[i], names[j]))				
					edge = pydot.Edge(names[i], names[j])	
					graph.add_edge(edge)
	graph.write_png(outFile) 
Example 19
Project: pyOpenAireTextClassifier   Author: tyiannak   File: textFeatureExtraction.py    Apache License 2.0 5 votes vote down vote up
def drawGraphFromSM(SM, names, outFile):
	fig = plt.figure(1)
	plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
	plt.show()
		
	gr = graph()

	namesNew = []
	for i,f in enumerate(names):	
		if sum(SM[i,:])>0:
			gr.add_nodes([f])
			namesNew.append(f)
			
	Max = SM.max()
	Mean = mean(SM)

	Threshold = Mean * 1.5
	for i in range(len(names)):
		for j in range(len(names)):
			if i<j:
				if SM[i][j] > 0:
					gr.add_edge((names[i], names[j]))
	# Draw as PNG
	dot = write(gr)
	gvv = gv.readstring(dot)
	gv.layout(gvv,'dot')
	gv.render(gvv,'png', outFile) 
Example 20
Project: pyplis   Author: jgliss   File: image.py    GNU General Public License v3.0 5 votes vote down vote up
def is_gray(self):
        """Check if image is gray image."""
        if self.img.ndim == 2:
            return True
        elif self.img.ndim == 3:
            return False
        else:
            raise Exception("Unexpected image dimension %s..." % self.img.ndim) 
Example 21
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 22
Project: LSDMappingTools   Author: LSDtopotools   File: raster_plotter_2d_ascii_chanfile_version.py    MIT License 5 votes vote down vote up
def cumulative_rainfall_catchment(hillshade_file, radar_data_totals):
    """
    Plots the catchment hillshade and overlays the total rainfalls accumulated
    during the model run.
    """
    label_size = 20
    #title_size = 30
    axis_size = 28

    import matplotlib.pyplot as pp
    import numpy as np
    import matplotlib.colors as colors
    import matplotlib.cm as cmx
    from matplotlib import rcParams
    import matplotlib.lines as mpllines
    
    #get data
    #hillshade, hillshade_header = read_flt(hillshade_file)
    
    hillshade, hillshade_header = read_ascii_raster(hillshade_file)
    rainfall_totals = np.loadtxt(radar_data_totals)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    
    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size      
    
    fig = pp.figure(1, facecolor='white',figsize=(10,7.5))
    ax = fig.add_subplot(1,1,1)
    
    plt.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray)
    plt.imshow(rainfall_totals, interpolation="none", alpha=0.2) 
Example 23
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMappingTools.py    MIT License 5 votes vote down vote up
def simple_density_plot_asc(rfname):

  import numpy as np, matplotlib.pyplot as plt
  from matplotlib import rcParams
  import matplotlib.colors as colors
  import matplotlib.cm as cmx

  label_size = 20
  #title_size = 30
  axis_size = 28

  # Set up fonts for plots
  rcParams['font.family'] = 'sans-serif'
  rcParams['font.sans-serif'] = ['Liberation Sans']
  rcParams['font.size'] = label_size 

  # get the data
  raster,header = read_ascii_raster(rfname)

  # now get the extent
  extent_raster = get_raster_extent_asc(header)

  #print extent_raster

  # make a figure, sized for a ppt slide
  fig = plt.figure(1, facecolor='white',figsize=(10,7.5))
  ax1 =  fig.add_subplot(1,1,1)
  im = ax1.imshow(raster, cmap='gray', extent = extent_raster)
  ax1.set_xlabel("Easting (m)")
  ax1.set_ylabel("Northing (m)")
  im.set_clim(0, np.max(raster))
  cbar = fig.colorbar(im, orientation='horizontal')
  cbar.set_label("Elevation in meters")  

  plt.show() 
Example 24
Project: Computable   Author: ktraunmueller   File: pyplot.py    MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 25
Project: neural-network-animation   Author: miloharper   File: pyplot.py    MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 26
Project: dimension-interpolation   Author: fargrat   File: optimize_pil.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def resize(img, index, component):
    saved = []

    # Numpy-Array in Pillow einlesen
    im = Image.fromarray(np.uint8(img), 'L')
    scale = config.getint('SCALE_FACTOR')
    # im = Image.open("../data/processed/cropped37.jpg").convert("L")
    width, height = im.size
    width *= scale
    height *= scale
    angle = 180

    # Bild um Faktor skalieren und ANTIALIAS als Interpolationsmethode wählen
    im = im.resize((width, height), Image.ANTIALIAS)

    if height > width:
        im = im.rotate(-90, expand=1)
        angle = 90

    img = np.array(im)

    # Bild optimieren
    thresh = threshold_otsu(img)
    img = img > 127

    #print("Saving to: ", config.get('RESULT_PATH') + index + "_optimized.jpg")
    plt.imsave(config.get('RESULT_PATH') + index + "_optimized.png", img, cmap=cm.gray)
    # Optimiertes Bild abspeichern
    saved.append((index + "_optimized.png", component, angle))

    return saved 
Example 27
Project: pyxao   Author: mikeireland   File: __init__.py    MIT License 5 votes vote down vote up
def show_seeing(dt=0.02,nt=51,wave=1e-6):
    """DEMO: Show the intensity and phase in the pupil plane, for a default
    atmosphere and a default wavefront"""
    print("Initializing")
    atm = Atmosphere()
    wf = Wavefront(wave=wave)
    wf.add_atmosphere(atm)
    print("Running")
    for i in range(nt):
        tic1=time.time()
        atm.evolve(dt*i)
        tic2=time.time()
        wf.pupil_field()
        tic3=time.time()
        im = wf.image()
        tic4=time.time()
        print("Times: {0:5.2f} {1:5.2f} {2:5.2f}".format(tic2-tic1,tic3-tic2,tic4-tic3))
        im /= np.max(im)
        plt.clf()
        hw = wf.sz/2*wf.m_per_px #half-width in metres
        plt.subplot(221)
        plt.imshow(np.abs(wf.field),cmap=cm.gray,extent=[-hw,hw,-hw,hw],vmax=2,interpolation='nearest')
        plt.title("Amplitude")
        plt.subplot(222)
        plt.imshow(np.angle(wf.field)*wf.pupil,extent=[-hw,hw,-hw,hw],vmax=2,interpolation='nearest')
        plt.title("Phase (T={0:6.2f})".format(dt*i))
        plt.subplot(223)
        hw_pix = int(np.radians(1./3600)*wf.sz*wf.m_per_px/wf.wave*2)
        plt.imshow(im[wf.sz-hw_pix:wf.sz+hw_pix,wf.sz-hw_pix:wf.sz+hw_pix],interpolation='nearest', cmap=cm.gist_heat,extent=[-1,1,-1,1])
        plt.title("Image")
        
        #Now find a perfectly phase-corrected image
        wf.field = np.abs(wf.field)
        im_corrected =wf.image()
        im_corrected /= np.max(im_corrected)
        plt.subplot(224)
        hw_pix = int(np.radians(1./3600)*wf.sz*wf.m_per_px/wf.wave*2)
        plt.imshow(np.arcsinh(np.minimum(im_corrected[wf.sz-hw_pix:wf.sz+hw_pix,wf.sz-hw_pix:wf.sz+hw_pix],.1)/1e-6),\
            interpolation='nearest', cmap=cm.gist_heat,extent=[-1,1,-1,1])
        plt.title("Corrected Image")
        plt.draw() 
Example 28
Project: pyxao   Author: mikeireland   File: atmosphere.py    MIT License 5 votes vote down vote up
def propagate_to_ground(self,wave=1e-6,dz=2e2,nprop=50):
        # AZ: dz is the distance over which to propagate the wavefront.
        """DEMO: Show a pretty movie of the full wavefront being propagated to ground level."""
        prop = ot.FresnelPropagator(self.sz,self.m_per_px, dz,wave)
        field = np.exp(2j*np.pi*self.phasescreens[0]/wave)
        for i in range(nprop):
            field = prop.propagate(field)
            plt.clf()
            hw = self.sz/2*self.m_per_px #half-width in metres
            plt.imshow(np.abs(field),cmap=cm.gray,interpolation='nearest',vmax=2,\
                extent=[-hw,hw,-hw,hw])
            plt.title("Field amplitude after {0:5.1f}m. RMS: {1:5.2f}".format((i+1)*dz, np.std(np.abs(field))))
            plt.draw() 
Example 29
Project: gmg   Author: btozer   File: objects.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self.file = None  # THE FULL FILE PATH TO THE SEGY DATA
        self.name = None  # THE NAME ASSIGNED TO THE DATA (str)
        self.dimensions = None
        self.mpl_actor = None  # THE MPL ACTOR ELEMENT (PLOTTING OBJECT)
        self.axis = None  # THE X AND Z AXIS LIMITS = X1, X2, Z1, Z2
        self.color_map = cm.gray  # THE COLOR SCALE USED TO PLOT THE DATA
        self.data = None  # THE XY DATA LOADED FROM INPUT FILE (numpy array)
        self.gain_positive = 4.0
        self.gain_neg = -self.gain_positive
        self.segy_show = False
        self.plot_list = None 
Example 30
Project: gmg   Author: btozer   File: gmg.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def segy_color_adjustment(self, event):
        if event.Id == 901:
            for s in range(0, len(self.segy_data_list)):
                if self.segy_data_list[s] is not None:
                    self.segy_data_list[s].mpl_actor.set_cmap(cm.gray)
        else:
            if event.Id == 902:
                for s in range(0, len(self.segy_data_list)):
                    if self.segy_data_list[s] is not None:
                        self.segy_data_list[s].mpl_actor.set_cmap(cm.seismic)
        # REDRAW MODEL
        self.draw() 
Example 31
Project: NanchiPlot   Author: JorgeDeLosSantos   File: app.py    MIT License 5 votes vote down vote up
def OnImage(self,event):
        setplot.set_default_params(self.axes,self.figure)
        X = self.data.grid_data.GetArrayData()
        rows,cols = X.shape
        self.axes.imshow(X, cmap=cm.gray)
        self.canvas.draw() 
Example 32
Project: pymake   Author: dtrckd   File: scaled_image.py    GNU General Public License v3.0 5 votes vote down vote up
def scaledimage(W, pixwidth=1, ax=None, grayscale=True):
    """
    Do intensity plot, similar to MATLAB imagesc()

    W = intensity matrix to visualize
    pixwidth = size of each W element
    ax = matplotlib Axes to draw on
    grayscale = use grayscale color map

    Rely on caller to .show()
    """

    # N = rows, M = column
    (N, M) = W.shape
    # Need to create a new Axes?
    if(ax == None):
        ax = plt.figure().gca()
    # extents = Left Right Bottom Top
    exts = (0, pixwidth * M, 0, pixwidth * N)
    if(grayscale):
        ax.imshow(W,
                  interpolation='nearest',
                  cmap=CM.gray,
                  extent=exts)
    else:
        ax.imshow(W,
                  interpolation='nearest',
                  extent=exts)

    ax.xaxis.set_major_locator(MT.NullLocator())
    ax.yaxis.set_major_locator(MT.NullLocator())
    return ax 
Example 33
Project: IBP_Linear_Gaussian_Latent_Factor_Model   Author: jaehyunjoo   File: scaledimage.py    GNU General Public License v3.0 5 votes vote down vote up
def scaledimage(W, pixwidth=1, ax=None, grayscale=True):
    """Do intensity plot, similar to MATLAB imagesc()."""
    # W = intensity matrix to visualize
    # pixwidth = size of each W element
    # ax = matplotlib Axes to draw on
    # grayscale = use grayscale color map
    # Rely on caller to .show()

    # N = rows, M = column
    (N, M) = W.shape
    # Need to create a new Axes?
    if(ax is None):
        ax = plt.figure().gca()
    # extents = Left Right Bottom Top
    exts = (0, pixwidth * M, 0, pixwidth * N)
    if(grayscale):
        ax.imshow(W,
                  interpolation='nearest',
                  cmap=cm.gray,
                  extent=exts)
    else:
        ax.imshow(W,
                  interpolation='nearest',
                  extent=exts)

    ax.xaxis.set_major_locator(mt.NullLocator())
    ax.yaxis.set_major_locator(mt.NullLocator())
    return ax 
Example 34
Project: end-to-end-multiview-lipreading   Author: lzuwei   File: plotting_utils.py    Apache License 2.0 5 votes vote down vote up
def show_image(data, shape, order='f', cmap=cm.gray):
    """
    display an image from a 1d vector
    :param data: 1d vector containing image information
    :param shape: actual image dimensions
    :param order: 'c' or 'f'
    :param cmap: colour map, defaults to grayscale
    :return:
    """
    img = data.reshape(shape, order=order)
    plt.imshow(img, cmap=cmap)
    plt.show() 
Example 35
Project: snippets   Author: jeremiedecock   File: label_on_contours_and_heat_map.py    MIT License 5 votes vote down vote up
def main():
    """The main function."""

    # Build data ################

    matplotlib.rcParams['xtick.direction'] = 'out'
    matplotlib.rcParams['ytick.direction'] = 'out'

    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)

    #Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    #Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    #Z = 10.0 * (Z2 - Z1)  # difference of Gaussians
    
    Z = X * np.exp(-X**2 - Y**2)


    # Plot data #################

    ## Plot contour
    #CS = plt.contour(X, Y, Z)
    #plt.clabel(CS, inline=1, fontsize=10)

    ## Plot heat map
    #im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    # Plot contour
    CS = ax.contour(X, Y, Z)
    ax.clabel(CS, inline=1, fontsize=10)

    # Plot heat map
    im = ax.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2))

    plt.show() 
Example 36
Project: SamPy   Author: sniemi   File: phaseretrievalresults.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plotStars(self, file, ext, xpos, ypos, rad=25):
        """
        """
        if ext == 1: chip = 2
        if ext == 4: chip = 1

        #manipulate data
        data = PF.open(file)[ext].data
        data[data <= 1.0] = 1.0
        data = N.log10(data)

        ax = P.subplot(111)
        b = P.gca()

        ims = ax.imshow(data,
                        origin='lower',
                        cmap=cm.gray,
                        interpolation=None,
                        vmin=0.0,
                        vmax=3.0)
        cb = P.colorbar(ims, orientation='horizontal')
        cb.set_label('$\log_{10}(Counts)$')

        #loop over xpos and ypos and ratio and draw circles
        count = 1
        for x, y in zip(xpos, ypos):
            cir = Circle((x + 1, y + 1), radius=rad, fc='none', ec='r')
            b.add_patch(cir)
            P.annotate('Star %i' % count,
                       xy=(x, y + 70),
                       horizontalalignment='center',
                       verticalalignment='center',
                       style='italic', size='xx-small',
                       color='red')
            count += 1

        P.title('Focus Stars of %s Chip %i' % (file[:-9], chip))

        P.savefig('%sStarsChip%i.pdf' % (file[:-7], chip))
        P.close() 
Example 37
Project: SamPy   Author: sniemi   File: plotting.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def PSF(self, datax, datay, dataz, output):
        '''
        Does not do very good job with matplotlib 0.99.0.
        The labels are somewhat tilted respect to the axis.
        '''
        fig = plt.figure()
        ax = Axes3D(fig)
        X, Y = N.meshgrid(datax, datay)
        ax.plot_surface(X, Y, dataz, rstride=1, cstride=1, cmap=cm.gray) #cm.gist_gray)
        #ax.plot_wireframe(X, Y, dataz, rstride=1, cstride=1)
        ax.set_xlabel('X Pixels')
        ax.set_ylabel('Y Pixels')
        ax.set_zlabel('Counts / s')
        P.savefig(output+self.type)
        P.close() 
Example 38
Project: SamPy   Author: sniemi   File: PhaseRetResults.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plotStars(self, file, ext, xpos, ypos, rad = 25):
        '''
        '''
        if ext == 1: chip = 2
        if ext == 4: chip = 1
        
        #manipulate data
        data = PF.open(file)[ext].data
        data[data <= 1.0] = 1.0
        data = N.log10(data)  
        
        ax = P.subplot(111)
        b = P.gca()
                
        ims = ax.imshow(data,
                        origin='lower',
                        cmap = cm.gray,
                        interpolation = None,
                        vmin = 0.0,
                        vmax = 3.0)
        cb = P.colorbar(ims, orientation='horizontal')
        cb.set_label('$\log_{10}(Counts)$')
        
        #loop over xpos and ypos and ratio and draw circles
        count = 1
        for x, y in zip(xpos, ypos):
            cir = Circle((x+1, y+1), radius = rad, fc = 'none', ec = 'r')
            b.add_patch(cir)
            P.annotate('Star %i' % count,
                        xy = (x, y+70), 
                        horizontalalignment='center',
                        verticalalignment='center',
                        style = 'italic', size = 'xx-small',
                        color='red')
            count += 1
        
        P.title('Focus Stars of %s Chip %i' % (file[:-9], chip))
        
        P.savefig('%sStarsChip%i.pdf' % (file[:-7], chip))       
        P.close() 
Example 39
Project: SamPy   Author: sniemi   File: STISCCDSpectroscopyFlat.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _plot50(self, flat, xcen, ycen, rad, fname):
        '''
        This function can be used to plot flat file images where
        dust motes have been circled. Will save the output figure
        to fname.pdf.
        @param flat: flat field array
        @param xcen: a list of x central coordinates for dust motes
        @param ycen: a list of y central coordinates for dust motes
        @param rad: a list of radius for dust motest   
        '''
        
        ax = PL.subplot(111)
        b = PL.gca()
        #P.title(fname)
        
        ims = ax.imshow(flat, origin='lower',
                        cmap = cm.gray,
                        interpolation = None,
                        vmin = 0.98,
                        vmax = 1.02)
        cb = PL.colorbar(ims, orientation='vertical')
        cb.set_label('Normalized Counts')
        
        #loop over xcen and ycen and ratio and draw circles
        for x, y, r in zip(xcen, ycen, rad):
            cir = Circle((x,y), radius=r, fc = 'none', ec = 'r')
            b.add_patch(cir)

        #PL.show()         
        PL.savefig(fname + '.pdf')       
        PL.close() 
Example 40
Project: SamPy   Author: sniemi   File: STISCCDSpectroscopyFlat.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _plot50(self, flat, xcen, ycen, rad, fname):
        """
        This function can be used to plot flat file images where
        dust motes have been circled. Will save the output figure
        to fname.pdf.
        :param flat: flat field array
        :param xcen: a list of x central coordinates for dust motes
        :param ycen: a list of y central coordinates for dust motes
        :param rad: a list of radius for dust motest   
        """

        ax = PL.subplot(111)
        b = PL.gca()
        #P.title(fname)

        ims = ax.imshow(flat, origin='lower',
                        cmap=cm.gray,
                        interpolation=None,
                        vmin=0.98,
                        vmax=1.02)
        cb = PL.colorbar(ims, orientation='vertical')
        cb.set_label('Normalized Counts')

        #loop over xcen and ycen and ratio and draw circles
        for x, y, r in zip(xcen, ycen, rad):
            cir = Circle((x, y), radius=r, fc='none', ec='r')
            b.add_patch(cir)

        #PL.show()         
        PL.savefig(fname + '.pdf')
        PL.close() 
Example 41
Project: Blackjack-Tracker   Author: martinabeleda   File: pyplot.py    MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 42
Project: dfc2019   Author: pubgeo   File: epipolar.py    MIT License 5 votes vote down vote up
def show_rectified_images(rimg1, rimg2):
    ax = pl.subplot(121)
    pl.imshow(rimg1, cmap=cm.gray)

    # Hack to get the lines span on the left image
    # http://stackoverflow.com/questions/6146290/plotting-a-line-over-several-graphs
    for i in range(1, rimg1.shape[0], int(rimg1.shape[0]/20)):
        pl.axhline(y=i, color='g', xmin=0, xmax=1.2, clip_on=False);

    pl.subplot(122)
    pl.imshow(rimg2, cmap=cm.gray)
    for i in range(1, rimg1.shape[0], int(rimg1.shape[0]/20)):
        pl.axhline(y=i, color='g'); 
Example 43
Project: cnidaria   Author: sauloal   File: pyplot.py    MIT License 5 votes vote down vote up
def gray():
    '''
    set the default colormap to gray and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='gray')
    im = gci()

    if im is not None:
        im.set_cmap(cm.gray)
    draw_if_interactive()


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 44
Project: dasp   Author: agb32   File: mypylab.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,window=None,startGtk=0,dims=2):
        self.dims=dims
        self.data=numpy.zeros((10,10),numpy.float32)
        self.data[:]=numpy.arange(10).astype(numpy.float32)
        self.deactivatefn=None#this can be set by the caller, eg to turn off buttons...
        
        self.win = gtk.Window()
        self.win.connect("destroy", self.quit)
        self.win.set_default_size(400,400)
        self.win.set_title("Window")
        self.cmap=colour.gray
        self.vbox = gtk.VBox()
        self.interpolation="nearest"#see pylab documantation for others.
        self.win.add(self.vbox)
        self.vbox.connect("button_press_event",self.buttonPress)
        self.fig = Figure(figsize=(5,4), dpi=50)
        self.ax=self.fig.add_subplot(111)
        self.fig.subplots_adjust(right=0.99,left=0.08,bottom=0.05,top=0.99)
        #self.ax.imshow(self.data,interpolation=self.interpolation)
        #print type(fig),dir(ax),dir(fig)
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.vbox.pack_start(self.canvas)
        self.toolbar = NavigationToolbar(self.canvas, self.win)
        self.vbox.pack_start(self.toolbar, False, False)
        self.mytoolbar=myToolbar(plotfn=self.plot)
        #self.toolbar.save_figure=self.mytoolbar.mysave
        self.vbox.pack_start(self.mytoolbar.toolbar,False,False)
        self.win.show_all()
        self.toolbar.hide()
        self.mytoolbar.toolbar.hide()
        self.active=1#will be set to zero once quit or window closed.
        self.toolbarVisible=0
        self.startedGtk=0
        self.update=0
        #self.plot()
        if startGtk==1 and gtk.main_level()==0:
            self.startedGtk=1
            thread.start_new_thread(gtk.main,()) 
Example 45
Project: pymps   Author: GiggleLiu   File: plotlattice.py    MIT License 5 votes vote down vote up
def __init__(self, radius=0.2, lw=2, color='#333333'):
        self.radius = radius
        self._cm = cm.gray
        self.lw = lw
        self.color = color 
Example 46
Project: augmentation   Author: BreastGAN   File: create_rcnn_dataset.py    Apache License 2.0 5 votes vote down vote up
def to_png(img, path):
    img = imutils.normalize(img.copy(), new_min=0, new_max=255)
    matplotlib.image.imsave(path, img, cmap=cm.gray) 
Example 47
Project: NivLink   Author: nivlab   File: moat.py    MIT License 4 votes vote down vote up
def plot_moat_heatmaps(info_with_aoi, H, contrast):
    """Plot raw data heatmaps with overlaid AoIs.
    
    Parameters
    ----------
    info_with_aoi : instance of `ScreenInfo`
        Eyetracking acquisition information with AoIs added.

    H: array, shape(xdim, ydim) 
        2D histogram of position in pixel space. 
    contrast : array, shape(0,1)
        Contrast for histogram plot. 
      
    Returns
    -------
    fig, ax : plt.figure
        Figure and axis of plot.
      
    Notes
    -----
    Requires matplotlib.
    """      

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(20, 20));
    axes[0,0].imshow(H, interpolation='bilinear', cmap=cm.gnuplot, clim=(contrast[0], contrast[1]));
    axes[0,0].imshow(info_with_aoi.indices[:,:,0].T, alpha = 0.2, cmap = cm.gray)
    axes[0,0].set_xticks([]);
    axes[0,0].set_yticks([]);
    axes[0,0].set_title('Simple vs. simple');

    axes[0,1].imshow(H, interpolation='bilinear', cmap=cm.gnuplot, clim=(contrast[0], contrast[1]));
    axes[0,1].imshow(info_with_aoi.indices[:,:,1].T, alpha = 0.2, cmap = cm.gray)
    axes[0,1].set_xticks([]);
    axes[0,1].set_yticks([]);
    axes[0,1].set_title('Compound vs. simple');

    axes[1,0].imshow(H, interpolation='bilinear', cmap=cm.gnuplot, clim=(contrast[0], contrast[1]));
    axes[1,0].imshow(info_with_aoi.indices[:,:,2].T, alpha = 0.2, cmap = cm.gray)
    axes[1,0].set_xticks([]);
    axes[1,0].set_yticks([]);
    axes[1,0].set_title('Simple vs. compound');

    axes[1,1].imshow(H, interpolation='bilinear', cmap=cm.gnuplot, clim=(contrast[0], contrast[1]));
    axes[1,1].imshow(info_with_aoi.indices[:,:,3].T, alpha = 0.2, cmap = cm.gray)
    axes[1,1].set_xticks([]);
    axes[1,1].set_yticks([]);
    axes[1,1].set_title('Compound vs. compound');

    return fig, axes 
Example 48
Project: NivLink   Author: nivlab   File: viz.py    MIT License 4 votes vote down vote up
def plot_heatmaps(info_with_aoi, raw_pos_data, contrast, config):
    """Plot raw data heatmaps with overlaid AoIs.
    
    Parameters
    ----------
    info_with_aoi : instance of `Screen`
        Eyetracking acquisition information with AoIs added.
    raw_pos_data: array, shape(xdim, ydim) 
        Raw x,y gaze data. 
    contrast : array, shape(0,1)
        Contrast for histogram plot. 
    config : int
        Specifies the aoi configuration we wish to display. 

    Returns
    -------
    fig, ax : plt.figure
        Figure and axis of plot.
      
    Notes
    -----
    Requires matplotlib.
    """      

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    from matplotlib.patches import Rectangle

    ## Remove NaNs.
    mask = ~np.any(np.isnan(raw_pos_data),axis=1)
    x = raw_pos_data[mask,0]
    y = raw_pos_data[mask,1]
    x_y = np.column_stack([x,y])

    ## Compute 2D histogram in pixel space. 
    xedges = np.arange(0,info_with_aoi.xdim+1)
    yedges = np.arange(0,info_with_aoi.ydim+1)
    H, xedges, yedges = np.histogram2d(x, y,bins=(xedges, yedges))
    H = H.T

    fig, ax = plt.subplots(1, 1, figsize=(20, 20));
    ax.imshow(H, interpolation='bilinear', cmap=cm.gnuplot, clim=(contrast[0], contrast[1]));
    ax.imshow(info_with_aoi.indices[:,:,config-1].T, alpha = 0.2, cmap = cm.gray)
    ax.set_xticks([]);
    ax.set_yticks([]);

    return fig, ax 
Example 49
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 4 votes vote down vote up
def colors():
    """
    This is a do-nothing function to provide you with help on how
    matplotlib handles colors.

    Commands which take color arguments can use several formats to
    specify the colors.  For the basic built-in colors, you can use a
    single letter

      =====   =======
      Alias   Color
      =====   =======
      'b'     blue
      'g'     green
      'r'     red
      'c'     cyan
      'm'     magenta
      'y'     yellow
      'k'     black
      'w'     white
      =====   =======

    For a greater range of colors, you have two options.  You can
    specify the color using an html hex string, as in::

      color = '#eeefff'

    or you can pass an R,G,B tuple, where each of R,G,B are in the
    range [0,1].

    You can also use any legal html name for a color, for example::

      color = 'red'
      color = 'burlywood'
      color = 'chartreuse'

    The example below creates a subplot with a dark
    slate gray background::

       subplot(111, facecolor=(0.1843, 0.3098, 0.3098))

    Here is an example that creates a pale turquoise title::

      title('Is this the best color?', color='#afeeee')

    """
    pass 
Example 50
Project: LSDMappingTools   Author: LSDtopotools   File: raster_plotter_2d_ascii_chanfile_version.py    MIT License 4 votes vote down vote up
def plot_ChiMValues_hillshade(hillshade_file, m_value_file):
    
    """
    Pass in a hillshade and chiMvalues flt file and plot the results over
    a greyscale hillshade
    """

    import matplotlib.pyplot as pp
    import matplotlib.cm as cm
    from matplotlib import rcParams
    import numpy as np
    
    #get data
    hillshade, hillshade_header = read_flt(hillshade_file)
    m_values, m_values_header = read_flt(m_value_file)
    
    #ignore nodata values    
    hillshade = np.ma.masked_where(hillshade == -9999, hillshade)    
    m_values = np.ma.masked_where(m_values == -9999, m_values)
    
    #fonts
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = 12  

    fig, ax = pp.subplots()
    
    #plot the arrays
    ax.imshow(hillshade, vmin=0, vmax=255, cmap=cm.gray)
    data = ax.imshow(m_values, interpolation='none', vmin=m_values.min(), vmax=m_values.max(), cmap=cm.jet)
    
    xlocs, xlabels = pp.xticks()
    ylocs, ylabels = pp.yticks()
   
    new_x_labels = np.linspace(hillshade_header[2],hillshade_header[2]+(hillshade_header[1]*hillshade_header[4]), len(xlocs))
    new_y_labels = np.linspace(hillshade_header[3],hillshade_header[3]+(hillshade_header[0]*hillshade_header[4]), len(ylocs))        
    
    new_x_labels = [str(x).split('.')[0] for x in new_x_labels] #get rid of decimal places in axis ticks
    new_y_labels = [str(y).split('.')[0] for y in new_y_labels][::-1] #invert y axis
    pp.xticks(xlocs[1:-1], new_x_labels[1:-1], rotation=30)  #[1:-1] skips ticks where we have no data
    pp.yticks(ylocs[1:-1], new_y_labels[1:-1])    
    
    fig.colorbar(data).set_label('M Values')
    pp.xlabel('Easting (m)')
    pp.ylabel('Northing (m)')
    
    pp.show()