如何将图像作为背景添加到 matplotlib 图(不是绘图,而是添加到“空白”ala set_face() )

Mal*_*irl 3 python image matplotlib subplot

我正在尝试将图像添加到 matplotlib 图的各个子图后面的“空白”。

与此主题类似的大多数讨论都是将图像添加到绘图本身,但是我还没有找到更改整个“画布”背景的方法。

我发现的最相似的功能是set_facecolor(),但是这只允许将单一颜色设置为背景。

fig, ax = plt.subplots(2,2)
fig.patch.set_facecolor('xkcd:mint green')
plt.show()
Run Code Online (Sandbox Code Playgroud)

电流输出

但是,我正在寻求一种解决方案来导入绘图后面的图像,类似于此(手动制作):

期望的输出

我已经用谷歌搜索,搜索了SO,并浏览了matplotlib文档,但我只得到了或者plt.imshow(image)set_facecolor()类似的结果。

Joh*_*anC 5

您可以使用与图形大小相同的虚拟子图,并将背景绘制到该子图上。

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

image = plt.imread('test.jpg') 

# make ticks white, for readability on colored background
mpl.rcParams.update({'xtick.color': "white",
                     'ytick.color': "white",
                     'axes.labelcolor': "white"}) 
# create a figure with 4 subplots, with the same aspect ratio as the image
width = 8
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(width, width * image.shape[0] / image.shape[1]))
for ax in np.ravel(axs):
    ax.patch.set_alpha(0.7) # make subplots semi-transparent

background_ax = plt.axes([0, 0, 1, 1]) # create a dummy subplot for the background
background_ax.set_zorder(-1) # set the background subplot behind the others
background_ax.imshow(image, aspect='auto') # show the backgroud image

# plot something onto the subplots
t = np.linspace(0, 8 * np.pi, 2000)
for i in range(2):
    for j in range(2):
        axs[i, j].plot(np.sin(t * (i + 2)), np.sin(t * (j + 4)))

# plt.tight_layout() gives a warning, as the background ax won't be taken into account,
# but normally the other subplots will be rearranged to nicely fill the figure
plt.tight_layout() 
plt.show()
Run Code Online (Sandbox Code Playgroud)

使用图像作为图形背景