You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib如何在图表左上角精准添加图片?代码问题排查

Matplotlib图表精确尺寸与左上角图片定位问题解决

原代码失效原因

  1. 图表尺寸不符:figsize设置的是包含边框、工具栏等元素的整体figure尺寸,plt.show()的显示窗口受GUI后端影响,实际像素会和预期偏差;且未消除figure的默认边距,导致有效绘图区域小于设置尺寸。
  2. 图片定位错误:
    • figure pixels坐标原点是整个figure的左下角,你设置的xy=(34,h-48)是因为默认边距占了左侧34像素,但这种硬编码偏移不通用。
    • zoom=1是按figure的dpi缩放图片,不是按原图片像素尺寸显示,导致图片大小不符合预期。

修正后的实现代码

import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.offsetbox import AnnotationBbox, OffsetImage

def plot_image(w, h):
    # 获取当前DPI,用于精确计算尺寸
    dpi = plt.rcParams['figure.dpi']
    # 按目标像素尺寸计算figure的英寸大小
    fig_width = w / dpi
    fig_height = h / dpi
    
    # 创建指定尺寸和DPI的figure
    fig, ax = plt.subplots(figsize=(fig_width, fig_height), dpi=dpi)
    # 消除所有边距,让绘图区域完全占满figure
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
    # 设置坐标轴范围与目标像素尺寸对齐
    ax.set_xlim(0, w)
    ax.set_ylim(0, h)
    
    # 加载48x48图片
    image_path = 'The Simpsons 48x48.png'
    image_data = Image.open(image_path)
    # 计算zoom值,确保图片按原像素尺寸显示
    zoom = 48 / dpi
    image_box = OffsetImage(image_data, zoom=zoom)
    
    # 定位图片到左上角:图片左下角坐标为(0, h-48),使用data坐标系与像素对齐
    anno_box = AnnotationBbox(image_box, xy=(0, h-48), xycoords='data', frameon=False)
    ax.add_artist(anno_box)
    
    # 添加测试文本
    ax.text(w/2, h/2, f'Requested: {w}x{h}', ha='center', va='center')
    
    # 保存图片时确保精确像素尺寸(显示窗口可能受GUI影响,保存更可靠)
    plt.savefig(f'test_{w}x{h}.png', dpi=dpi, bbox_inches='tight', pad_inches=0)
    plt.show()

plot_image(640, 480)
plot_image(800, 600)
plot_image(1024, 768)

关键修正点说明

  • 精确尺寸控制:通过dpi换算英寸尺寸,配合subplots_adjust消除边距,再用savefig指定dpi和无内边距参数,确保保存的图片是精确的目标像素尺寸。
  • 图片精准定位:使用与像素对齐的data坐标系,直接设置图片左下角坐标为(0, h-48),实现左上角贴合;通过zoom=48/dpi保证图片显示为原48x48像素大小。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:14:59