Python 如何使用matplotlib在绘图的角上插入小图像?

Python 如何使用matplotlib在绘图的角上插入小图像?,python,django,image,matplotlib,Python,Django,Image,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",autosc

我想要的其实很简单:我有一个名为“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

如果您希望图像位于实际图形的拐角处(而不是轴的拐角处),请查看

也许是这样的?(使用PIL读取图像):

另一个选项是,如果希望图像成为地物宽度/高度的固定部分,则创建一个“虚拟”轴,并使用
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()

现在有一种更简单的方法,使用新命令(需要matplotlib>3.0)

此命令允许将一组新轴定义为现有
对象的子对象。这样做的好处是,您可以使用适当的
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')

此方法的优点是,当轴重新缩放时,图像将自动缩放

有什么方法可以相对于右下角定位此徽标吗?@Jared-尝试以下方式:
fig.figimage(im,fig.bbox.xmax-宽度,高度)
有没有一种方法可以独立于dpi放置图像?@tillsten-有几种不同的方法,但都很粗糙。您想要什么独立于dpi,图像的大小、位置或两者?如果两者都是,一个简便的技巧是制作一个新的轴(手动指定其位置和大小),使用
imshow
,使用
axis('off')
关闭刻度,等等。各种
OffsetImage
功能是另一种方式,但如果采用这种方式,大小与dpi无关。@tilsten-事实上,现在我想起来了,如果您只想以独立于dpi的方式将图像放置在另一个角落,那么有一种更简单的方法。我将用一个例子更新答案。
# 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')