[英]Matplotlib draw rectangle over image, rectangle specified in image coordinates
我正在绘制这样的图像
fig, ax = plt.subplots()
ax.imshow(im, cmap = "gray")
我想使用以下参数在图像顶部绘制一个矩形(在图像坐标中)
(0,0,240,210)
(顶部,左侧,宽度,高度)
矩形补丁的文档说,第一个参数是一个元组,指定矩形的“左下角”。
rect = mpatches.Rectangle((0, 0 + 210), 240, 210, fill = False, linewidth = 2, edgecolor = randHex())
ax.add_patch(rect)
绘制此图形后,矩形显示在错误的位置,我不确定为什么。 我认为在matplotlib的坐标系中使用的图像坐标之间存在某种坐标系不匹配。
编辑:如果我只是使用(0, 0)
它可以正常工作,但这与文档不一致。
如果轴从上到下,则矩形的底部实际上是顶部(从数据坐标来看)。 但是,总是正确的是
plt.Rectangle((x, y), w, h)
从(x,y)
扩展到(x+w, y+h)
。
因此,当我们在x和y轴各自方向不同的轴上绘制相同的矩形plt.Rectangle((1,2), 2, 1)
时,它看起来会有所不同。
import matplotlib.pyplot as plt
def plot_rect(ax):
rect = plt.Rectangle((1,2), 2, 1)
ax.add_patch(rect)
ax.scatter([1], [2], s=36, color="k", zorder=3)
fig, axs = plt.subplots(2,2)
xlims = ((-4,4), (-4,4), (4,-4), (4,-4))
ylims = ((-4,4), (4,-4), (-4,4), (4,-4))
for ax, xlim, ylim in zip(axs.flat, xlims, ylims):
plot_rect(ax)
ax.set(xlim=xlim, ylim=ylim)
plt.show()
我猜您读错了文档! 哈哈好吧,坐标从矩形的左上角开始。
(x, y, w, h)
(x,y)是左上角,其中(w,y)是矩形的宽度和高度。
希望能帮助到你。 和平了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.