简体   繁体   English

matplotlib:matshow 在图像顶部有网格线

[英]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.我正在使用 pyplot.matshow 绘制矩阵,并尝试使用plt.gca().set_axisbelow(True)使网格线显示在绘图后面,但它们始终位于顶部。 How can I make the grid lines plot behind a matshow?如何在 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. print(matplotlib.rcparams['grid.color']显示默认的网格颜色:'#b0b0b0')。这样网格在绘图的黑色部分是不可见的。

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.在下面的代码中,我将图像更改为 20x20,以使黑色方块很好地居中并移除较低的 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()

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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