子图中的不连续轴 - python matplotlib

时间:2015-07-17 11:28:30

标签: python matplotlib plot

我想要将y轴分成两部分。下部应具有正常比例,而上部应按比例缩放10倍。

我已经找到了一些关于如何制作具有断开的x或y轴的图的示例,例如: http://matplotlib.org/examples/pylab_examples/broken_axis.html

但是当我想将它应用于2x2网格图中的单个子图时,我不明白如何实现这一点。如果这很重要,我会设置如下图:

fig = plt.figure()
fig.set_size_inches(8, 6)

fig.add_subplot(221)
[...]
fig.add_subplot(222)
[...]

2 个答案:

答案 0 :(得分:0)

你不能设置一个4x4的网格轴,并且有3个轴跨越该空间的2x2吗?然后,您想要打开轴的图可以覆盖剩余的2x2空间作为部件ax4_upperax4_lower

ax1 = plt.subplot2grid((4, 4), (0, 0), colspan=2, rowspan=2)
ax2 = plt.subplot2grid((4, 4), (0, 2), colspan=2, rowspan=2)
ax3 = plt.subplot2grid((4, 4), (2, 0), colspan=2, rowspan=2)
ax4_upper = plt.subplot2grid((4, 4), (2, 2), colspan=2, rowspan=1)
ax4_lower = plt.subplot2grid((4, 4), (3, 2), colspan=2, rowspan=1)

然后,您可以为ylimax4_upper设置ax4_lower值,并按示例显示继续:

# hide the spines between ax4 upper and lower
ax4_upper.spines['bottom'].set_visible(False)
ax4_lower.spines['top'].set_visible(False)
ax4_upper.xaxis.tick_top()
ax4_upper.tick_params(labeltop='off') # don't put tick labels at the top
ax4_lower.xaxis.tick_bottom()

d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax4_upper.transAxes, color='k', clip_on=False)
ax4_upper.plot((-d,+d),(-d,+d), **kwargs)      # top-left diagonal
ax4_upper.plot((1-d,1+d),(-d,+d), **kwargs)    # top-right diagonal

kwargs.update(transform=ax4_lower.transAxes)  # switch to the bottom axes
ax4_lower.plot((-d,+d),(1-d,1+d), **kwargs)   # bottom-left diagonal
ax4_lower.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-right diagonal

plt.show()

2x2 with broken axes

答案 1 :(得分:0)

您可以use gridspec布置轴的形状和位置:

import numpy as np
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

gs = gridspec.GridSpec(4, 2)
ax00 = plt.subplot(gs[:2, 0])
ax01 = plt.subplot(gs[:2, 1])
ax10a = plt.subplot(gs[2, 0])
ax10b = plt.subplot(gs[3, 0])
ax11 = plt.subplot(gs[2:, 1])

x = np.linspace(-1, 1, 500)
y = 100*np.cos(10*x)**2*np.exp(-x**2)
for ax in (ax00, ax01, ax10a, ax10b, ax11):
    ax.plot(x, y)

ax10a.set_ylim(60, 110)
ax10b.set_ylim(0, 10) 

ax10a.spines['bottom'].set_visible(False)
ax10b.spines['top'].set_visible(False)
ax10a.xaxis.tick_top()
ax10a.tick_params(labeltop='off') # don't put tick labels at the top
ax10b.xaxis.tick_bottom()

d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax10a.transAxes, color='k', clip_on=False)
ax10a.plot((-d,+d),(-d,+d), **kwargs)      # top-left diagonal
ax10a.plot((1-d,1+d),(-d,+d), **kwargs)    # top-right diagonal

kwargs.update(transform=ax10b.transAxes)  # switch to the bottom axes
ax10b.plot((-d,+d),(1-d,1+d), **kwargs)   # bottom-left diagonal
ax10b.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-right diagonal

plt.tight_layout()
plt.show()

enter image description here