我试图将一幅图像添加到matplotlib图形的各个子情节后面的"空白"中.

大多数类似这一主题的讨论都是为情节本身添加图像,但我还没有遇到改变整体画布背景的方法.

我找到的最相似的函数是set_facecolor(),但这只允许将单一 colored颜色 设置为背景.

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

current output

然而,我正在寻找一种解决方案,以导入情节背后的图像,类似于此(手动制作):

desired output

我已经在谷歌上搜索过了,搜索过了,并查看了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相关问答推荐

使用numpy提取数据块

需要计算60,000个坐标之间的距离

将pandas Dataframe转换为3D numpy矩阵

删除字符串中第一次出现单词后的所有内容

我如何使法国在 map 中完全透明的代码?

如何使用pytest来查看Python中是否存在class attribution属性?

在pandas中使用group_by,但有条件

当递归函数的返回值未绑定到变量时,非局部变量不更新:

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

使用Python和文件进行模糊输出

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

Flash只从html表单中获取一个值

OpenCV轮廓.很难找到给定图像的所需轮廓

为什么在FastAPI中创建与数据库的连接时需要使用生成器?

使用Python异步地持久跟踪用户输入

查看pandas字符列是否在字符串列中

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

仅取消堆叠最后三列

从`end_date`回溯,如何计算以极为单位的滚动统计量?