Python imshow no axis

How to remove x axis and y axis of an image in imshow in python

Question: As a reference, same question but for : Matplotlib plots: removing axis, legends and white spaces It is not obvious in embedded image on selected answer that there are fat white margins around the plot, as stackoverflow page background is white. My second choice would be to display x = row number, y = column number

How to remove x axis and y axis of an image in imshow in python

from numpy import random import matplotlib.pyplot as plt data = random.random((5,5)) img = plt.imshow(data, interpolation='nearest') img.set_cmap('hot') plt.axis('off') plt.savefig("test.png", bbox_inches='tight')

How to remove x axis and y axis of an image in imshow, Python answers related to “how to remove x axis and y axis of an image in imshow in python”. matplotlib reverse y axis. plot image without axes python. remove …

In a matplotlib figure window (with imshow), how can I remove, hide, or redefine the displayed position of the mouse? [duplicate]

I am using ipython with matplotlib, and I show images in this way:

(started up with: ipython —pylab)

figure() im = zeros([256,256]) #just a stand-in for my real images imshow(im) 

Now, as I move the cursor over the image, I see the location of the mouse displayed in the lower left corner of the figure window. The numbers displayed are x = column number, y = row number. This is very plot-oriented rather than image-oriented. Can I modify the numbers displayed?

  1. My first choice would be to display x = row number*scalar, y = column number*scalar
  2. My second choice would be to display x = row number, y = column number
  3. My third choice is to not display the numbers for the mouse location at all
Читайте также:  Css пауза после анимации

Can I do any of these things? I’m not even sure what to call that little mouse-over test display widget. Thanks!

You can do this quite simply on a per axis basis by simply re-assigning format_coord of the Axes object, as shown in the examples.

format_coord is any function which takes 2 arguments (x,y) and returns a string (which is then displayed on the figure.

If you want to have no display simply do:

ax.format_coord = lambda x, y: '' 

If you want just the row and column (with out checking)

scale_val = 1 ax.format_coord = lambda x, y: 'r=%d,c=%d' % (scale_val * int(x + .5), scale_val * int(y + .5)) 

If you want to do this on every iimage you make, simply define the wrapper function

def imshow(img, scale_val=1, ax=None, *args, **kwargs): if ax is None: ax = plt.gca() im = ax.imshow(img, *args, **kwargs) ax.format_coord = lambda x, y: 'r=%d,c=%d' % (scale_val * int(x + .5), scale_val * int(y + .5)) ax.figure.canvas.draw() return im 

which with out much testing I think should more-or-less be drop-in replacement for plt.imshow

Yes, you can. But it’s harder than you’d think.

The mouse-tracking label you see is generated by calls to matplotlib.axes.Axes.format_coord in response to mouse tracking. You have to create your own Axes class (overriding format_coord to do what you want it to do), then instruct matplotlib to use it in place of the default one.

Make your own Axes subclass
from matplotlib.axes import Axes class MyRectilinearAxes(Axes): name = 'MyRectilinearAxes' def format_coord(self, x, y): # Massage your data here -- good place for scalar multiplication if x is None: xs = '. ' else: xs = self.format_xdata(x * .5) if y is None: ys = '. ' else: ys = self.format_ydata(y * .5) # Format your label here -- I transposed x and y labels return 'x=%s y=%s' % (ys, xs) 
Register your Axes subclass
from matplotlib.projections import projection_registry projection_registry.register(MyRectilinearAxes) 
Create a figure and with your custom axes
figure() subplot(111, projection="MyRectilinearAxes") 
Draw your data as before
im = zeros([256,256]) #just a stand-in for my real images imshow(im) 

Imshow remove axis Code Example, axes axis off. plt turn off one axis. plt show without axis. plt.show () axis off. turn off x axis matplotlib. plt off axis. make axis invisible matplotlib. matplotlib …

Remove boxes around imshow when sharing X axis

When I try to stack several imshow elements, some extra white space appears around them in the vertical axis and the titles appear too close to the other figures.

I think that both issues are caused by the sharex=True but I do not know how to solve them.

fig.tight_layout() almost solves this problem, but it is incompatible with the colour bar on the side and makes some squares smaller than others.

The code that generates the image is

# Values is a [(ndarray, string)] fig, axes = plt.subplots(len(values), sharex=True) for ax, (value, plot_name) in zip(axes, values): im = ax.imshow(value, vmax=1.0, vmin=0.0) ax.set_title(plot_name) # (Hack) Apply on the last one plt.xticks(range(values.shape[1]), ticks, rotation=90) plt.colorbar(im, ax=axes.ravel().tolist()) fig.savefig(output_name, bbox_inches="tight") 

and an example image is:

Adding the gridspec_kw= argument to the plt.subplots constructor made it work for me. That controls the vertical space between the subplots I believe

ticks = ["blah" for i in range(17)] # Values is a [(ndarray, string)] values = [(np.random.randn(3,17), "Title") for i in range(3)] fig, axes = plt.subplots(len(values), sharex=True, gridspec_kw=) for ax, (value, plot_name) in zip(axes, values): im = ax.imshow(value, vmax=1.0, vmin=0.0) ax.set_title(plot_name) # (Hack) Apply on the last one plt.xticks(range(values[0][0].shape[1]), ticks, rotation=90) plt.colorbar(im, ax=axes.ravel().tolist()) plt.show() 

Unfortunately the aspect of the plots cannot be set to «equal» when sharex=True is used. There might be two solutions:

Not sharing axes

Sharing axes is not really necessary, since all subplots anyway have the same dimension. So the idea would be not to share any axes, but simply remove the ticklabels of the upper plots.

import matplotlib.pyplot as plt import numpy as np values = [np.random.rand(3,10) for i in range(3)] fig, axes = plt.subplots(len(values)) for i, (ax, value) in enumerate(zip(axes, values)): im = ax.imshow(value, vmax=1.0, vmin=0.0) ax.set_title("title") ax.set_xticks(range(value.shape[1])) if i != len(axes)-1: ax.set_xticklabels([]) else: plt.setp(ax.get_xticklabels(), rotation=90) plt.colorbar(im, ax=axes.ravel().tolist()) plt.show() 

Using ImageGrid

Using ImageGrid from the mpl_toolkits.axes_grid1 module provides a grid specifically for plots of equal aspects. It can be used as follows. One main advantage here is that the colorbar would automatically be the same size as the subplots.

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid values = [np.random.rand(3,10) for i in range(3)] axes = ImageGrid(plt.figure(), 111, nrows_ncols=(3,1), axes_pad=0.3, share_all=True, cbar_location="right", cbar_mode="single", cbar_size="2%", cbar_pad=0.15, label_mode = "L" ) for i, (ax, value) in enumerate(zip(axes, values)): im = ax.imshow(value, vmax=1.0, vmin=0.0) ax.set_title("title") ax.set_xticks(range(value.shape[1])) plt.setp(ax.get_xticklabels(), rotation=90) ax.cax.colorbar(im) plt.show() 

Remove axes matplotlib Code Example, from numpy import random import matplotlib.pyplot as plt data = random.random((5,5)) img = plt.imshow(data, interpolation=’nearest’) …

Matplotlib get clean plot (remove all decorations)

As a reference, same question but for imshow() : Matplotlib plots: removing axis, legends and white spaces

It is not obvious in embedded image on selected answer that there are fat white margins around the plot, as stackoverflow page background is white.

The following answer by @unutbu works for imshow() but not for general plot() . Also aspect=’normal is deprecated since version 1.2.

So how to save plot() as image, without any decorations?

ax.set_axis_off() , or equivalently, ax.axis(‘off’) toggles the axis lines and labels off. To remove more whitespace, you could use

fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0) 

Or to remove all whitespace up to the axis’ boundaries, use

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) fig.savefig('/tmp/extent.png', bbox_inches=extent) 

These commands will work equally well with either ax.imshow(data) or ax.plot(data) .

import numpy as np import matplotlib.pyplot as plt data = np.arange(1,10).reshape((3, 3)) fig, ax = plt.subplots() ax.plot(data) ax.axis('off') # https://stackoverflow.com/a/4328608/190597 (Joe Kington) # Save just the portion _inside_ the axis's boundaries extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) fig.savefig('/tmp/extent.png', bbox_inches=extent) fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0) 

I just learned that @unutbu’s answer does work with plot() too, if we remove aspect=’normal’ from plot() directive:

data = np.arange(1,10).reshape((3, 3)) fig = plt.figure() fig.set_size_inches(1, 1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.plot(data) plt.savefig('test.png') 

But, I still wonder if all this is really necessary to get clean plot?
Shouldn’t be there obvious argument to savefig() that can handle this?

Python — In a matplotlib figure window (with imshow), You can do this quite simply on a per axis basis by simply re-assigning format_coord of the Axes object, as shown in the examples. …

Источник

Оцените статью