首页 > 解决方案 > 如何将图形(3x3 子图)插入 matplotlib python 的子图中

问题描述

我想在子图中插入一个 3x3 图形。这里这里显示了一个类似的问题,但解决方案似乎不起作用(我认为)。

任何人都可以提供一些代码(尽可能简单)来产生这个:

在此处输入图像描述

如果有人可以提供帮助,我会很高兴,在此先感谢。任何答案或评论将不胜感激。

标签: pythonmatplotlibinsertfiguresubplot

解决方案


我使用这个答案创建了一个解决方案。我添加的部分写在带有注释的行下方#。我承认这并不普遍和完美,但在我看来仍然足以完成工作。

import matplotlib.pyplot as plt
import numpy as np

def add_subplot_axes(ax, rect): # This is the function in the linked answer
    fig = plt.gcf()
    box = ax.get_position()
    width = box.width
    height = box.height
    inax_position  = ax.transAxes.transform(rect[0:2])
    transFigure = fig.transFigure.inverted()
    infig_position = transFigure.transform(inax_position)    
    x = infig_position[0]
    y = infig_position[1]
    width *= rect[2]
    height *= rect[3]  
    subax = fig.add_axes([x,y,width,height])
    x_labelsize = subax.get_xticklabels()[0].get_size()
    y_labelsize = subax.get_yticklabels()[0].get_size()
    x_labelsize *= rect[2]**0.5
    y_labelsize *= rect[3]**0.5
    subax.xaxis.set_tick_params(labelsize=x_labelsize)
    subax.yaxis.set_tick_params(labelsize=y_labelsize)
    return subax

# Modified part below

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
x_start, y_start = 0.4, 0.4
for i in range(3):
    for j in range(3):
        rect = [x_start+0.2*i, y_start+0.2*j, 0.15, 0.15]
        ax_ = add_subplot_axes(ax,rect)
        ax_.tick_params(labelsize=6)
plt.show()

在此处输入图像描述


推荐阅读