加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Matplotlib:如何绘制图像而不是点?

发布时间:2020-12-20 10:35:04 所属栏目:Python 来源:网络整理
导读:我想将图像列表读入 Python / Matplotlib,然后在图形中绘制此图像而不是其他标记(如点).我已尝试使用imshow但我没有成功,因为我无法将图像移动到另一个位置并适当地缩放它.也许有人有个好主意:) 解决方法 有两种方法可以做到这一点. 使用imshow绘制图像,并根
我想将图像列表读入 Python / Matplotlib,然后在图形中绘制此图像而不是其他标记(如点).我已尝试使用imshow但我没有成功,因为我无法将图像移动到另一个位置并适当地缩放它.也许有人有个好主意:)

解决方法

有两种方法可以做到这一点.

>使用imshow绘制图像,并根据您希望图像所在的位置设置范围kwarg.
>在AnnotationBbox中使用OffsetImage.

第一种方式是最容易理解的,但第二种方式具有很大的优势. k注释框方法将允许图像在放大时保持恒定大小.使用imshow将图像的大小与图的数据坐标联系起来.

以下是第二个选项的示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage,AnnotationBbox
from matplotlib.cbook import get_sample_data

def main():
    x = np.linspace(0,10,20)
    y = np.cos(x)
    image_path = get_sample_data('ada.png')
    fig,ax = plt.subplots()
    imscatter(x,y,image_path,zoom=0.1,ax=ax)
    ax.plot(x,y)
    plt.show()

def imscatter(x,image,ax=None,zoom=1):
    if ax is None:
        ax = plt.gca()
    try:
        image = plt.imread(image)
    except TypeError:
        # Likely already an array...
        pass
    im = OffsetImage(image,zoom=zoom)
    x,y = np.atleast_1d(x,y)
    artists = []
    for x0,y0 in zip(x,y):
        ab = AnnotationBbox(im,(x0,y0),xycoords='data',frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x,y]))
    ax.autoscale()
    return artists

main()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读