python - 如何向子图添加轴?

标签 python matplotlib subplot

我有一系列使用 matplotlib.pyplot.subplots 绘制的相关函数,并且我需要在每个子图中包含相应函数的缩放部分。

我开始像解释的那样做 here当只有一个图但没有子图时它可以完美地工作。

如果我用子图来做,我只会得到一个图表,其中包含所有函数。这是我到目前为止所得到的示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 10, 0.01)
sinx = np.sin(x)
tanx = np.tan(x)

fig, ax = plt.subplots( 1, 2, sharey='row', figsize=(9, 3) )

for i, f in enumerate([sinx, cosx]):
    ax[i].plot( x, f, color='red' )
    ax[i].set_ylim([-2, 2])

    axx = plt.axes([.2, .6, .2, .2],)
    axx.plot( x, f, color='green' )
    axx.set_xlim([0, 5])
    axx.set_ylim([0.75, 1.25])

plt.show(fig)

该段代码给出了下图:

enter image description here

如何在每个子图中创建新的轴和绘图?

最佳答案

如果我理解得好,你可以使用inset_axes

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import inset_axes


x = np.arange(-10, 10, 0.01)
sinx = np.sin(x)
tanx = np.tan(x)

fig, ax = plt.subplots( 1, 2, sharey='row', figsize=(9, 3) )

for i, f in enumerate([sinx, tanx]):
    ax[i].plot( x, f, color='red' )
    ax[i].set_ylim([-2, 2])

    # create an inset axe in the current axe:
    inset_ax = inset_axes(ax[i],
                          height="30%", # set height
                          width="30%", # and width
                          loc=10) # center, you can check the different codes in plt.legend?
    inset_ax.plot(x, f, color='green')
    inset_ax.set_xlim([0, 5])
    inset_ax.set_ylim([0.75, 1.25])
plt.show()

inset_axe

关于python - 如何向子图添加轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479863/

相关文章:

python - 将文件保存在当前目录的文件夹中

python - 在 django admin 中仅按年份过滤

python - Dijkstra 的算法只是 BFS,您还计算节点权重吗?

matplotlib - dpi 与图形大小的关系

python - 在子图之外放置多个颜色条 (matplotlib)

java - JFreeChart - 在 CombinedDomainXYPlot 中显示/隐藏子图

python - Python中调用C函数的问题

python - FuncAnimation 仅在窗口大小调整后启动

python - 在 seaborn lmplot 中访问轴对象

Python:使用 for 循环创建 matplotlib 子图