想要绘制出如下类型坐标轴断开的图,matplotlib中并没有直接可用的API,但是官方给出了一个demo: broken axis.py
大概说下思路:画出两个共享X轴,完全相同的图,下图取消上边界,下图取消下边界,然后再使用plot画两组平行线就大功告成。
参照官网例子画的堆积图代码
def respond_mode_bar(self):
labels = ['Braking','Right','Left','R&B','L&B']
# color_list = ['silver', 'red', 'blue', 'orange', 'deepskyblue']
# color_list = ['blue', 'orange', 'green', 'red', 'olive']
x = list(self.sub_list)
y = np.zeros((len(self.sub_list), len(labels)), dtype=np.float)
y0 = np.zeros(len(self.sub_list), dtype=np.float)
# fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
gs = gridspec.GridSpec(2,1, height_ratios=[3,1], hspace=0.15)
fig = plt.figure(figsize=(8, 4.5))
ax1 = fig.add_subplot(gs[0,:])
ax2 = fig.add_subplot(gs[1,:], sharex=ax1)
ax1.set_ylim(70, 100)
ax2.set_ylim(0, 10)
ax1.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.xaxis.tick_top()
ax1.tick_params(labeltop='off')
ax2.xaxis.tick_bottom()
for idx, sub in enumerate (self.sub_list):
sub = str(sub).zfill(4)
y[idx,:] = np.array(self.data_dict[sub]['respond_mode'])
for ii in range(len(labels)):
if ii==0: ax1.bar(x, y[:,ii], align='center', \
label = labels[ii], width=0.6)
if ii==0: ax2.bar(x, y[:,ii], align='center', \
label = labels[ii], width=0.6)
else:
y0 = y0 +y[:, ii-1]
ax1.bar(x, y[:,ii], bottom=y0, align='center', \
label = labels[ii], width=0.6)
ax2.bar(x, y[:,ii], bottom=y0, align='center', \
label = labels[ii], width=0.6)
d = .01 # how big to make the diagonal lines in axes coordinates
kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
ax1.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
ax1.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal
kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d, +d), (1 - d*3, 1 + d*3), **kwargs) # bottom-left diagonal
ax2.plot((1 - d, 1 + d), (1 - d*3, 1 + d*3), **kwargs) # bottom-right diagonal
plt.xlabel('Subject index')
ax1.set_ylabel('Percentage (%)')
plt.legend(loc=(0.65, 0.1), title='Evasive Maneuvers', \
facecolor='w', framealpha=1)
plt.savefig(self.fig_path+sub+'_respond_mode.png', dpi=300, transparent=True)
plt.show()
官方参考
https://matplotlib.org/examples/pylab_examples/broken_axis.html