gpt4 book ai didi

python - 在 matplotlib imshow 中调整网格线和刻度线

转载 作者:IT老高 更新时间:2023-10-28 20:24:10 35 4
gpt4 key购买 nike

我正在尝试绘制一个值矩阵,并希望添加网格线以使值之间的边界更清晰。不幸的是,imshow 决定将刻度线定位在每个体素的中间。有没有可能

a) 移除勾号,但将标签保留在同一位置,并且
b) 在像素边界之间添加网格线?

import matplotlib.pyplot as plt
import numpy as np

im = plt.imshow(np.reshape(np.random.rand(100), newshape=(10,10)),
interpolation='none', vmin=0, vmax=1, aspect='equal');
ax = plt.gca();
ax.set_xticks(np.arange(0, 10, 1));
ax.set_yticks(np.arange(0, 10, 1));
ax.set_xticklabels(np.arange(1, 11, 1));
ax.set_yticklabels(np.arange(1, 11, 1));

图像没有网格线并且刻度线位置错误 enter image description here

ax.grid(color='w', linestyle='-', linewidth=2)

网格线位置错误的图像:

enter image description here

最佳答案

Serenity 建议的解决方案代码:

plt.figure()
im = plt.imshow(np.reshape(np.random.rand(100), newshape=(10,10)),
interpolation='none', vmin=0, vmax=1, aspect='equal')

ax = plt.gca();

# Major ticks
ax.set_xticks(np.arange(0, 10, 1))
ax.set_yticks(np.arange(0, 10, 1))

# Labels for major ticks
ax.set_xticklabels(np.arange(1, 11, 1))
ax.set_yticklabels(np.arange(1, 11, 1))

# Minor ticks
ax.set_xticks(np.arange(-.5, 10, 1), minor=True)
ax.set_yticks(np.arange(-.5, 10, 1), minor=True)

# Gridlines based on minor ticks
ax.grid(which='minor', color='w', linestyle='-', linewidth=2)

生成的图像: enter image description here

关于python - 在 matplotlib imshow 中调整网格线和刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38973868/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com