在图像上绘制网格线

时间:2017-11-28 09:24:02

标签: matplotlib matplotlib-basemap

我关注this answer,但我没有每隔10步获得一次网格线:

import matplotlib.pyplot as plt

plt.figure()
img=ims[0].copy()
dx, dy = 10,10

# Custom (rgb) grid color
grid_color = -1500

# Modify the image to include the grid
img[:,::dy] = grid_color
img[::dx,:] = grid_color

plt.imshow(img,'gray',interpolation='none',vmin=-1500,vmax=2258)

enter image description here

1 个答案:

答案 0 :(得分:0)

为了确保实际显示图像中的每个像素,您需要确保绘制图像,使图像中的一个像素大于或等于屏幕上的一个像素。

示例:如果图形的dpi为100且高度为4.5英寸,并且每边的边距为10%,则会正确显示350像素的图像,

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(6,4.5))
plt.subplots_adjust(top=0.9, bottom=0.1)
img=np.random.rand(350,350)
dx, dy = 10,10

grid_color = -1
img[:,::dy] = grid_color
img[::dx,:] = grid_color

plt.imshow(img,'gray',vmin=-1,vmax=1)
plt.show()

enter image description here

如果图形的dpi为100且高度为3.2英寸,并且每边都有10%的边距,则350像素的图像将不会显示每个像素,因此您得到以下输出,

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(6,3.2))
plt.subplots_adjust(top=0.9, bottom=0.1)
img=np.random.rand(350,350)
dx, dy = 10,10

grid_color = -1
img[:,::dy] = grid_color
img[::dx,:] = grid_color

plt.imshow(img,'gray',vmin=-1,vmax=1)
plt.show()

enter image description here

因此,即使对于后一种情况,为了获得网格,this answer是更好的方法。您可以创建一个网格并设置网格的线宽,这样总是0.72点(= 1pixel @ 100dpi)。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

plt.figure(figsize=(6,3.2))
plt.subplots_adjust(top=0.9, bottom=0.1)
img=np.random.rand(350,350)

plt.imshow(img,'gray',vmin=-1,vmax=1)

plt.minorticks_on()
plt.gca().xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(10))
plt.gca().yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(10))
plt.grid(which="both", linewidth=0.72,color="k")
plt.tick_params(which="minor", length=0)

plt.show()

enter image description here