【问题标题】:OffsetImage shows up different on screen and in PDF when aligning the image to the figure border将图像与图形边框对齐时,OffsetImage 在屏幕和 PDF 中显示不同
【发布时间】:2015-12-17 14:08:09
【问题描述】:

我想在一个图形上插入一个缩放的图像并将其与右图形边框对齐。以下在交互式窗口中以及保存为 png 时可以正常工作, 但是当另存为pdf时,图像太靠左了。我怎样才能得到这两种情况的正确行为?如果 savefig 和 figure 设置相同,也会发生这种情况。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage
import numpy as np
fig = plt.figure(dpi=100)
image = np.ones((200, 200))
ob = OffsetImage(image, zoom=0.5)
rend = fig.canvas.get_renderer()
w, h, x, d =  ob.get_extent(rend)
fig.images.append(ob)
ob.set_offset((fig.bbox.xmax-w, 0))
plt.show()
fig.savefig("bla.pdf", dpi=100)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以下代码对填充和边界框更明确,对我来说对 png 和 pdf 给出了相同的结果(matplotlib 1.4.3,python 2.7)。

    import matplotlib.pyplot as plt
    from matplotlib.offsetbox import OffsetImage
    import numpy as np
    
    fig = plt.figure(figsize=(8,6))
    image = np.ones((200, 200))
    ob = OffsetImage(image, zoom=0.5)
    rend = fig.canvas.get_renderer()
    w, h, x, d =  ob.get_extent(rend)
    fig.images.append(ob)
    ob.set_offset((fig.bbox.xmax-w, 0))
    fig.savefig("bla.pdf",figsize=(8,6),
                           bbox_inches='tight', 
                           pad_inches=0)
    

    您的代码版本(即使删除了plt.show())为我提供了一个空的pdf文档。至于上述工作的原因,我想这可能是matplotlib 的错误,或者可能是用于保存 pdf 的坐标 system 与更多所见即所得的显示/png 图的差异。也可以是 matplotlib 模板,在这种情况下,answer 可能会有所帮助...

    【讨论】:

    • 乍一看似乎有效:图像仍然放错了位置,但由于bbox_inches = 'tight',它将通过增加pdf的大小来包含。
    • 实际问题似乎是由于 pdf 始终以 72 dpi 计算而 OffsetImage 忽略了这一点。
    • 抱歉,没有意识到还是不对。除了光栅图形的分辨率外,PDF 显然不使用 dpi 设置。设置plt.figure(figsize=(width, height)) 是否有帮助,因为这会影响 PDF。
    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多