首页 > 解决方案 > 将 bbox_inches 设置为 'tight' 进行保存会更改显示坐标

问题描述

我的问题是对这个问题的一种跟进。我使用接受的答案中提出的解决方案将一些图像作为刻度标签:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.image import BboxImage,imread
from matplotlib.transforms import Bbox

# define where to put symbols vertically
TICKYPOS = -.6

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
plt.xlim((0,10))
plt.ylim((0,10))

# Remove tick labels
ax.get_xaxis().set_ticklabels([])

# Go from data coordinates to display coordinates
lowerCorner = ax.transData.transform((.8,TICKYPOS-.2))
upperCorner = ax.transData.transform((1.2,TICKYPOS+.2))

bbox_image = BboxImage(Bbox([lowerCorner,upperCorner]),
                       norm = None,
                       origin=None,
                       clip_on=False)

bbox_image.set_data(imread('thumb.png'))

ax.add_artist(bbox_image)

其中thumb.png是我想作为刻度标签放置的图像示例。

然后我保存图像,plt.savefig("bbox_large.png")它完美地工作: 预期结果,thumb.png 被正确定位。

不幸的是,图片周围还有很多空白区域。我尝试使用删除它plt.savefig("bbox_tight.png",bbox_inches='tight')。但是定位搞砸了:

thumb.png 不再正确定位。


据我对matplotlib的理解,问题在于实际改变显示坐标系的bbox_inches='tight'选项savefig,即原点不在同一个地方。该图以某种方式正确显示,但似乎添加到轴的艺术家的坐标不会自动更新。

我尝试使用以下方法考虑额外的艺术家:

plt.savefig("bbox_tight_extra.png",bbox_extra_artists=[bbox_image],bbox_inches='tight')

但它给出了相同的结果。

我还尝试使用事件管理器手动更新显示坐标:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.image import BboxImage,imread
from matplotlib.transforms import Bbox

def ondraw(event):
    # Go from data coordinates to display coordinates
    lowerCorner = ax.transData.transform((.8,TICKYPOS-.2))
    upperCorner = ax.transData.transform((1.2,TICKYPOS+.2))

    bbox_image = BboxImage(Bbox([lowerCorner,upperCorner]),
                           norm = None,
                           origin=None,
                           clip_on=False)

    bbox_image.set_data(imread('thumb.png'))
    ax.add_artist(bbox_image)

# define where to put symbols vertically
TICKYPOS = -.6

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
plt.xlim((0,10))
plt.ylim((0,10))

# Remove tick labels
ax.get_xaxis().set_ticklabels([])

fig.canvas.mpl_connect('draw_event', ondraw)

但它也给出了相同的结果。我假设这是因为我没有明确使用event变量,因此我没有使用更新的显示坐标系,transData也就是说我使用的不是正确的。


如何避免图像位置混乱bbox_inches='tight'

标签: pythonmatplotlibdrawing

解决方案


推荐阅读