Skip to main content
 首页 » 编程设计

python之如何将图形(3x3 子图)插入 matplotlib python 的子图中

2024年11月24日8yjmyzz

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

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

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

请您参考如下方法:

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

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