matplotlib - 在 matplotlib 的子图中嵌入小图

标签 matplotlib plot embedding axes subplot

如果您想在较大的绘图中插入一个小绘图,您可以使用 Axes ,例如 here .

问题是我不知道如何在子图中执行相同的操作。

我有几个子图,我想在每个子图内绘制一个小图。 示例代码如下所示:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()

for i in range(4):
    ax = fig.add_subplot(2,2,i)
    ax.plot(np.arange(11),np.arange(11),'b')

    #b = ax.axes([0.7,0.7,0.2,0.2]) 
    #it gives an error, AxesSubplot is not callable

    #b = plt.axes([0.7,0.7,0.2,0.2])
    #plt.plot(np.arange(3),np.arange(3)+11,'g')
    #it plots the small plot in the selected position of the whole figure, not inside the subplot

有什么想法吗?

最佳答案

我编写了一个与 plt.axes 非常相似的函数。您可以使用它来绘制您的子图。有一个例子...

import matplotlib.pyplot as plt
import numpy as np

#def add_subplot_axes(ax,rect,facecolor='w'): # matplotlib 2.0+
def add_subplot_axes(ax,rect,axisbg='w'):
    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]  # <= Typo was here
    #subax = fig.add_axes([x,y,width,height],facecolor=facecolor)  # matplotlib 2.0+
    subax = fig.add_axes([x,y,width,height],axisbg=axisbg)
    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
    
def example1():
    fig = plt.figure(figsize=(10,10))
    ax = fig.add_subplot(111)
    rect = [0.2,0.2,0.7,0.7]
    ax1 = add_subplot_axes(ax,rect)
    ax2 = add_subplot_axes(ax1,rect)
    ax3 = add_subplot_axes(ax2,rect)
    plt.show()

def example2():
    fig = plt.figure(figsize=(10,10))
    axes = []
    subpos = [0.2,0.6,0.3,0.3]
    x = np.linspace(-np.pi,np.pi)
    for i in range(4):
        axes.append(fig.add_subplot(2,2,i))
    for axis in axes:
        axis.set_xlim(-np.pi,np.pi)
        axis.set_ylim(-1,3)
        axis.plot(x,np.sin(x))
        subax1 = add_subplot_axes(axis,subpos)
        subax2 = add_subplot_axes(subax1,subpos)
        subax1.plot(x,np.sin(x))
        subax2.plot(x,np.sin(x))
if __name__ == '__main__':
    example2()
    plt.show()

enter image description here

关于matplotlib - 在 matplotlib 的子图中嵌入小图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17458580/

相关文章:

python - 在 C++ 中获取 Python 函数参数名称

python - 带有 imshow 的 matplotlib 图的 x 轴日期

python - Matplotlib 增加 x 轴上点之间的间距

python - 如何在 matplotlib 中的行上绘制一系列点?

r - 使用rgl包R将固定标题放置在交互式3D图中

javascript - Tableau JS 筛选器 : Using javascript API, 将筛选器从一个仪表板移动到另一个仪表板

matplotlib - 如何在 matplotlib 中叠加 shapefile

python - 在绘图外显示一行文本

r - map View 图例缩放

linux - itextpdf 字体未嵌入 Linux