在 matplotlib 的 x 轴中中断//[重复]
- 2025-02-11 09:50:00
- admin 原创
- 74
问题描述:
描述我想要实现的目标的最好方式是使用我自己的图像:
现在我在光谱图中有很多死区,特别是在 5200 和 6300 之间。我的问题很简单,我该如何添加一个看起来类似于这样的小 // 中断(图片取自网络):
我正在为我的情节使用这个设置:
nullfmt = pyplot.NullFormatter()
fig = pyplot.figure(figsize=(16,6))
gridspec_layout1= gridspec.GridSpec(2,1)
gridspec_layout1.update(left=0.05, right=0.97, hspace=0, wspace=0.018)
pyplot_top = fig.add_subplot(gridspec_layout1[0])
pyplot_bottom = fig.add_subplot(gridspec_layout1[1])
pyplot_top.xaxis.set_major_formatter(nullfmt)
我很确定这可以通过 gridpsec 实现,但如果能提供一个详细介绍如何实现这一点的高级教程,我将不胜感激。
如果这个问题之前已经在 stackoverflow 上处理过,那么我也很抱歉,但我已经广泛寻找正确的程序gridSpec
,但仍然一无所获。
我已经做到了这一点,基本上就是这样:
但是,我的断线并不像我想要的那样陡峭......我该如何改变它们?(我使用了下面的示例答案)
解决方案 1:
您可以直接调整matplotlib 示例以在 x 轴上进行中断:
"""
Broken axis example, where the x-axis will have a portion cut out.
"""
import matplotlib.pylab as plt
import numpy as np
x = np.linspace(0,10,100)
x[75:] = np.linspace(40,42.5,25)
y = np.sin(x)
f, (ax, ax2) = plt.subplots(1, 2, sharey=True, facecolor='w')
# plot the same data on both axes
ax.plot(x, y)
ax2.plot(x, y)
ax.set_xlim(0, 7.5)
ax2.set_xlim(40, 42.5)
# hide the spines between ax and ax2
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params(labelright='off')
ax2.yaxis.tick_right()
# This looks pretty good, and was fairly painless, but you can get that
# cut-out diagonal lines look with just a bit more work. The important
# thing to know here is that in axes coordinates, which are always
# between 0-1, spine endpoints are at these locations (0, 0), (0, 1),
# (1, 0), and (1, 1). Thus, we just need to put the diagonals in the
# appropriate corners of each of our axes, and so long as we use the
# right transform and disable clipping.
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=ax.transAxes, color='k', clip_on=False)
ax.plot((1-d, 1+d), (-d, +d), **kwargs)
ax.plot((1-d, 1+d), (1-d, 1+d), **kwargs)
kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d, +d), (1-d, 1+d), **kwargs)
ax2.plot((-d, +d), (-d, +d), **kwargs)
# What's cool about this is that now if we vary the distance between
# ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
# the diagonal lines will move accordingly, and stay right at the tips
# of the spines they are 'breaking'
plt.show()
为了您的目的,只需绘制两次数据(每个轴一次,ax
然后适当ax2
设置您的xlim
s )。“断线”应该移动以匹配新的断线,因为它们是在相对轴坐标而不是数据坐标中绘制的。
断线只是在两个点之间绘制的未裁剪的绘图线。例如,在第一个轴上绘制点和ax.plot((1-d, 1+d), (-d, +d), **kwargs)
之间的断线:这是右下角的断线。如果要更改梯度,请适当更改这些值。例如,要使这个更陡峭,请尝试(1-d, -d)
`(1+d, +d)`ax.plot((1-d/2, 1+d/2), (-d, +d), **kwargs)
解决方案 2:
xnx 提供的解决方案是一个好的开始,但还有一个问题,即两个图之间的 x 轴比例不同。如果左图的范围和右图的范围相同,则这不是问题,但如果它们不相等,子图仍将使两个图的宽度相等,因此两个图之间的 x 轴比例将不同(xnx 的示例就是这种情况)。我制作了一个包brokenaxes来处理这个问题。
扫码咨询,免费领取项目管理大礼包!