Search code examples
pythonnumpymatplotlibscikit-imageimshow

Matplotlib subplot missing grid


I am trying to plot two graphs.
First one displayed randomly generated pixels and the second one eroded one.
When I plot those subplots first one does not show the grid, also Y axis numbering are reversed and origin point shifted a little bit.
Could you please advice how can i fix those issues?

enter image description here

Here is my code below:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from skimage.morphology import disk,erosion

x=np.random.randint(2,size=(10,10))
se=disk(1)
y=erosion(x,se)

fig, (ax0, ax1) = plt.subplots(1,2, figsize=(10,5))
cmap = mpl.colors.ListedColormap(['w', 'k'])

ax0.set_xticks(np.arange(0, 10, 1))
ax0.set_yticks(np.arange(0, 10, 1))
ax0.set_title("Input image")

ax1.set_xticks(np.arange(0, 10, 1))
ax1.set_yticks(np.arange(0, 10, 1))
ax1.set_title("Eroded Image")

ax0.imshow(x,interpolation='none', cmap=cmap, norm=norm)
ax1.imshow(y,interpolation='none', cmap=cmap, norm=norm)

plt.rc('grid', linestyle="-", color='red')
plt.grid(True)
plt.show()

Solution

  • Here the code to reverse the y axis:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from skimage.morphology import disk,erosion
    
    x=np.random.randint(2,size=(10,10))
    se=disk(1)
    y=erosion(x,se)
    
    fig, (ax0, ax1) = plt.subplots(1,2, figsize=(10,5))
    cmap = mpl.colors.ListedColormap(['w', 'k'])
    
    ax0.set_xticks(np.arange(0, 10, 1))
    ax0.set_yticks(np.arange(0, 10, 1))
    ax0.set_title("Input image")
    
    ax1.set_xticks(np.arange(0, 10, 1))
    ax1.set_yticks(np.arange(0, 10, 1))
    ax1.set_title("Eroded Image")
    
    ax0.imshow(x,interpolation='none', cmap=cmap)
    ax1.imshow(y,interpolation='none', cmap=cmap)
    
    plt.rc('grid', linestyle="-", color='red')
    ax0.invert_yaxis()
    ax1.invert_yaxis()
    
    plt.grid(True)
    plt.show()
    

    just use the .invert_yaxis() method after plotting the content. This the result:

    enter image description here

    Regarding the ticks: you are plotting a matrix through imshow(), so the x and y values are not continuous along their axis, they are concentreted in the cells of the matrix. The ticks that imshow() shows are referred to the center of each cells, because this is the information you are interested in. There is not a 'origin' that pass through the intersection of a 'x' and 'y' axes in a carthesian plane, because this is not a carthesian plane. You are translating the content of a matrix in an image, so imshow() shows you the ticks at each cell center.