python - 根据值向网格图添加边框

标签 python matplotlib

我想知道你是否能帮我解决这个问题。我有一个由 0 和 1 组成的网格,如果它是 1,我想向绘图单元格区域添加边框颜色。我使用 imshow 生成根据值着色的网格,例如:

a = np.random.randint(2, size=(10,10))

im = plt.imshow(a, cmap='Blues', interpolation='none', vmin=0, vmax=1, aspect='equal')

Grid

但是,我找不到要为 imshow 中的每个网格单元更改的任何边框属性。我读过 add_patch 可以用来在某些点放置一个矩形来模拟使用轴值的边框,但是有没有比循环和逐单元应用更好的方法?

最佳答案

没有内置函数可以对 imshow 边缘进行部分着色。最简单的选择可能确实是为每个单元格绘制一个矩形。

import matplotlib.pyplot as plt
import numpy as np

a = np.random.randint(2, size=(10,10))

im = plt.imshow(a, cmap='Blues', interpolation='none', vmin=0, vmax=1, aspect='equal')

def rect(pos):
    r = plt.Rectangle(pos-0.5, 1,1, facecolor="none", edgecolor="k", linewidth=2)
    plt.gca().add_patch(r)

x,y = np.meshgrid(np.arange(a.shape[1]),np.arange(a.shape[0]))
m = np.c_[x[a.astype(bool)],y[a.astype(bool)]]
for pos in m:
    rect(pos)

plt.show()

enter image description here

关于python - 根据值向网格图添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51432498/

相关文章:

python - 如何将多个元素分配给单个列表变量

python - 更改 Seaborn Boxplot 上的框和点分组色调

python - 更改 matplotlib fiddle 图的颜色

python - 如何将二值图像表示为图形,轴为高度和宽度尺寸,数据为像素

python - MatPlotLib Python - 来自颜色传感器的 RGB 值用于更改线点的颜色

python - 从 html 列表返回 json 字符串

python - 使用 matlab 运行 python 脚本

python - 使用 Python 从 Plotly 获取 &lt;script&gt; 和 <div> 标签

python - 如何在 python 中复制 Arduino 函数 lowByte?

python - 在 matplotlib 中自定义颜色 - 热图