【问题标题】:matplotlib: how to put picture to a specific point of data-coordinate systemmatplotlib:如何将图片放到数据坐标系的特定点
【发布时间】:2020-11-22 08:52:59
【问题描述】:

我正在尝试通过数据坐标系中的给定坐标在图中的特定位置添加图片。然而它的运行有点出乎意料。这是我写的一段代码sn-p:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(5,5))

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.grid('on')

x = np.arange(0, 1, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
ax.plot(x, y)

im_orange = plt.imread('./test100x100_orange.png')
im_blue = plt.imread('./test100x100_blue.png')

x0, y0 = ax.transData.transform((0,0))
print('transData(0,0) = {}'.format(ax.transData.transform((0,0))))

ax.figure.figimage(im_orange, alpha=0.5)
ax.figure.figimage(im_blue, x0, y0, alpha=0.5)

ax.transData.transform((0,0)) 返回transData(0,0) = [45. 45.],这是出乎意料的,因为它不代表图上 (0,0) 的实际位置。这是结果图像:

我的基本问题是如何将图片左下角精确地放在数据坐标中的 (0,0) 点?如果可能,请解释 matplotlib 的这种行为。

更新。上面有一些实验。我已经在 3 种模式下运行了一个稍微修改过的脚本(下面由 Iammuratc 提供,但使用 plt.savefig() 代替):

  1. 从 python 控制台(复制和粘贴):
  2. Python 脚本(类似于 python test.py: 结果和以前一样。
  3. ipython 来自 Jupiter Notebook: 子选项 A:plt.show()

子选项 B:plt.savefig()

现在更加混乱了..

【问题讨论】:

    标签: python image matplotlib


    【解决方案1】:

    它对我有用。您可以检查图像数组以防它们被移动。

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    im_orange  = np.zeros((128,128,3),'uint8')
    im_orange[:,:,0] = 255
    
    im_blue = np.zeros((128,128,3),'uint8')
    im_blue[:,:,2] = 255
    
    
    fig, ax = plt.subplots(figsize=(5,5))
    
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.grid('on')
    
    x = np.arange(0, 1, 0.005)
    y = np.exp(-x/2.) * np.sin(2*np.pi*x)
    ax.plot(x, y)
    
    # im_orange = plt.imread('./test100x100_orange.png')
    # im_blue = plt.imread('./test100x100_blue.png')
    
    x0, y0 = ax.transData.transform((0,0))
    print('transData(0,0) = {}'.format(ax.transData.transform((0,0))))
    
    ax.figure.figimage(im_orange,x0,y0, alpha=0.5)
    ax.figure.figimage(im_blue, x0, y0, alpha=0.5)
    
    plt.show()
    

    【讨论】:

    • 我是在 Jupiter notebook 上工作的吗?
    • 我不这么认为。但是只是为了尝试它是否有效,您可以在终端中运行代码,然后查看。
    • 只需运行几个实验(见上文主要部分)。目前我还没有具体的想法来解释它为什么会这样。
    • ax.figure.figimage(im_orange, alpha=0.5) 为什么不在此行中添加x0,y0?这应该将两个图像都放在原点上。
    • 我这样做是为了演示。它实际上不应该影响每张单独的图片在情节中的位置。即使我按照你说的那样做,它只会将两个矩形放在错误的位置。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多