簡體   English   中英

如何使用matplotlib在繪圖的角落插入小圖像?

[英]How to insert a small image on the corner of a plot with matplotlib?

我想要的非常簡單:我有一個名為“logo.png”的小圖像文件,我想將其顯示在繪圖的左上角。 但是您在 matplotlib 示例庫中找不到任何示例。

我正在使用 django,我的代碼是這樣的:

def get_bars(request)
    ...
    fig = Figure(facecolor='#F0F0F0',figsize=(4.6,4))
    ...
    ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",autoscale_on=True)
    ax1.bar(ind,values,width=width, color='#FFCC00',edgecolor='#B33600',linewidth=1)
    ...
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

如果您希望圖像位於實際圖形的角落(而不是軸的角落),請查看figimage

也許像這樣? (使用 PIL 讀取圖像):

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('/home/jofer/logo.png')
height = im.size[1]

# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255

fig = plt.figure()

plt.plot(np.arange(10), 4 * np.arange(10))

# With newer (1.0) versions of matplotlib, you can 
# use the "zorder" kwarg to make the image overlay
# the plot, rather than hide behind it... (e.g. zorder=10)
fig.figimage(im, 0, fig.bbox.ymax - height)

# (Saving with the same dpi as the screen default to
#  avoid displacing the logo image)
fig.savefig('/home/jofer/temp.png', dpi=80)

plt.show()

替代文字

另一種選擇,如果您想讓圖像成為圖形寬度/高度的固定分數,則創建一個“虛擬”軸並使用imshow將圖像放入其中。 這樣圖像的大小和位置就獨立於 DPI 和圖形的絕對大小:

import matplotlib.pyplot as plt
from matplotlib.cbook import get_sample_data

im = plt.imread(get_sample_data('grace_hopper.jpg'))

fig, ax = plt.subplots()
ax.plot(range(10))

# Place the image in the upper-right corner of the figure
#--------------------------------------------------------
# We're specifying the position and size in _figure_ coordinates, so the image
# will shrink/grow as the figure is resized. Remove "zorder=-1" to place the
# image in front of the axes.
newax = fig.add_axes([0.8, 0.8, 0.2, 0.2], anchor='NE', zorder=-1)
newax.imshow(im)
newax.axis('off')

plt.show()

在此處輸入圖片說明

現在有一個更簡單的方法,使用新的inset_axes命令(需要 matplotlib >3.0)。

此命令允許將一組新軸定義為現有axes對象的子項。 這樣做的好處是您可以使用適當的transform表達式以任何您喜歡的單位定義插入軸,例如軸分數或數據坐標。

所以這是一個代碼示例:

# Imports
import matplotlib.pyplot as plt
import matplotlib as mpl

# read image file
with mpl.cbook.get_sample_data(r"C:\path\to\file\image.png") as file:
arr_image = plt.imread(file, format='png')

# Draw image
axin = ax.inset_axes([105,-145,40,40],transform=ax.transData)    # create new inset axes in data coordinates
axin.imshow(arr_image)
axin.axis('off')

這種方法的優點是您的圖像將在您的軸重新縮放時自動縮放!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM