python - 如何将图像作为背景添加到 matplotlib 图(不是绘图,而是添加到 "whitespace"ala set_face() )

标签 python image matplotlib subplot

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

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

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

fig, ax = plt.subplots(2,2)
fig.patch.set_facecolor('xkcd:mint green')
plt.show()

current output

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

desired output

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

最佳答案

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

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

using an image as figure background

关于python - 如何将图像作为背景添加到 matplotlib 图(不是绘图,而是添加到 "whitespace"ala set_face() ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73898848/

相关文章:

python:如何从 feature_importances 中获取真实的特征名称

android - 使用android API = 8在背景图像上旋转透明png图像

java - 链接到动态网页中的图像

python - 更改线图中特定线的线宽 pandas/matplotlib

python-3.x - PathCollection' 对象没有属性 legend_elements''

python - Pandas -日期时间的累计总和并每天重新开始

python - 计算非常低的pvalues Python

python - 在 Python 中获取繁忙的 CPU 数量

android - SimpleDraweeView 在 fresco 中缩放图像后不调整大小

Python gmplot 'centerLat' 未定义