轴间纵横比

2024-09-30 01:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

引用barcode_demo示例,稍微修改一下添加图像:

from matplotlib.pyplot import figure, savefig, cm
import numpy as np

img = np.random.rand(500, 200)

axprops = dict(xticks=[], yticks=[])
barprops = dict(aspect='auto', cmap=cm.binary, interpolation='nearest')

fig = figure()

ax = fig.add_axes([0.3, 0.3, 0.6, 0.6], **axprops)
ax.imshow(img, **barprops)

x = np.array([img[y, :].sum() for y in xrange(img.shape[0])])
x = np.column_stack((x,) * 10).reshape(x.shape[0], 10)
ax = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops)
ax.imshow(x, **barprops)

x = np.array([img[:, x].sum() for x in xrange(img.shape[1])])
x = np.row_stack((x,) * 10).reshape(10, x.shape[0])
ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops)
ax.imshow(x, **barprops)

savefig('auto.png')

导致图像不符合纵横比(如预期):

auto.png

如果我将barpropsdict中的aspect参数设置为“equal”(这看起来像matplotlib中的默认值),我会得到以下图像:

equal.png

有没有简单的方法根据纵横比绘制图像,并绘制这两个“条形码”以匹配绘制的图像?你知道吗


Tags: 图像importaddimgmatplotlibnpfig绘制
1条回答
网友
1楼 · 发布于 2024-09-30 01:32:51

imshow的aspectkwarg以数据坐标而不是图形坐标来设置纵横比。对你来说,最简单的办法就是把这个数字变成正方形。我可以通过将figure声明更改为:

fig = figure(figsize=(7, 7))

然后得到

enter image description here

也可以根据图形的纵横比做一些计算,并在调用fig.add_axes时使用它,这样轴本身的纵横比就是您所期望的,但是对于这个图形来说,这只会给您留下很多无用的空白。你知道吗

相关问题 更多 >

    热门问题