简体   繁体   中英

matplotlib: matshow has grid lines on top of image

I'm using pyplot.matshow to plot a matrix, and am trying to use plt.gca().set_axisbelow(True) to make the gridlines show behind the plot but they are always on top. How can I make the grid lines plot behind a matshow?

import numpy as np
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
plt.rcParams['axes.axisbelow'] = True

m = np.zeros((21, 21))
m[14:17, 12:14] = -0.1

plt.matshow(np.ma.masked_equal(m, 0), cmap=ListedColormap(['k', 'w']), extent=(0.5, 20.5, 20.5, 0.5))
plt.xticks(range(1, 21));
plt.yticks(range(1, 21));
plt.gca().set_axisbelow(True)
plt.grid()

Note: edited to plot only nonzero parts as noted in comments.

You could change the color of the grid to the same color as the squares (instead of the default dark grey). So, 'black' in the case of the example in the question. ( print(matplotlib.rcparams['grid.color'] shows the default grid color: '#b0b0b0'). That way the grid is invisible over the black parts of the plot.

Experiment with line style and/or line width to make the grid less prominent.

In the code below I changed the image to 20x20 to have the black squares nicely centered and removed the lower xticks. The colors don't need to be black and white, though the grid will only be invisible over the squares of the same color as the grid.

import numpy as np
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

m = np.zeros((20, 20))
for i in range(20):
    for j in range(20):
        if 45 <= abs(i-9.5)**2 + abs(j-9.5)**2 <= 65:
            m[i, j] = -0.1

plt.matshow(m, cmap=ListedColormap(['indigo', 'gold']), extent=(0.5, 20.5, 20.5, 0.5))
plt.xticks(range(1, 21))
plt.yticks(range(1, 21))
plt.tick_params(axis='x', bottom=False)
plt.grid(c='indigo', ls=':', lw='0.4')
plt.show()

示例图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM