Matplotlib:如何绘制图像而不是点? [英] Matplotlib: How to plot images instead of points?

查看:489
本文介绍了Matplotlib:如何绘制图像而不是点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像列表读入Python / Matplotlib,然后在图形中绘制此图像而不是其他标记(如点)。我尝试过imshow但是我没有成功,因为我不能将图像移动到另一个位置并适当地缩放它。也许有人有个好主意:)

解决方案

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


  1. 使用 imshow 使用范围 kwarg设置图像基于您想要图像的位置。

  2. AnnotationBbox OffsetImage $ c>。

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

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

  import numpy as np 
从matplotlib.offsetbox导入matplotlib.pyplot作为plt
导入来自matplotlib.cbook的OffsetImage,AnnotationBbox
导入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,y,image,ax = None,zoom = 1):
如果ax为None:
ax = plt.gca()
try:
image = plt.imread (图片)
除了TypeError:
#可能已经是一个数组...
传递
im = OffsetImage(image,zoom = z oom)
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()
返回艺术家

main()


I want to read a list of images into Python/Matplotlib and then plot this images instead of other markers (like points) in a graph. I have tried with imshow but I didn't succeed, because I cannot shift the image to another position and scale it appropriately. Maybe somebody has a good idea : )

解决方案

There are two ways to do this.

  1. Plot the image using imshow with the extent kwarg set based on the location you want the image at.
  2. Use an OffsetImage inside an AnnotationBbox.

The first way is the easiest to understand, but the second has a large advantage. kThe annotation box approach will allow the image to stay at a constant size as you zoom in. Using imshow will tie the size of the image to the data coordinates of the plot.

Here's an example of the second option:

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, y, 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()

这篇关于Matplotlib:如何绘制图像而不是点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆