我有一系列使用 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)
该段代码给出了下图:
如何在每个子图中创建新的轴和绘图?
最佳答案
如果我理解得好,你可以使用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()
关于python - 如何向子图添加轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479863/