如何移除Matplotlib中多变量时间序列子图间的空白区域
消除Matplotlib上下子图间空白的解决方案
要保留坐标轴的同时消除子图间的空白,只需对代码做以下3处修改:
- 创建子图时通过
gridspec_kw设置垂直间距为0 - 隐藏上方子图的x轴刻度与标签,避免和下方子图重叠
- 调用
tight_layout()优化整体布局,防止元素被裁剪
修改后的完整代码如下:
#@title Animate Define # Display Parameter start = 0 end = 1024 Xt = X_unseen[start:end] yp = y_pred[start:end] yt = y_true[start:end] # Get mask of every class for prediction bl_pred = yp == 0 p_pred = yp == 1 qrs_pred = yp == 2 t_pred = yp == 3 # get mask of every class for ground truth bl_true = yt == 0 p_true = yt == 1 qrs_true = yt == 2 t_true = yt == 3 # 修改1:设置子图垂直间距为0 fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 8), gridspec_kw={'hspace': 0}) # Plotting for prediction prev_class = None start_idx = start for i in range(start, end): current_class = None if bl_pred[i]: current_class = 'grey' elif p_pred[i]: current_class = 'orange' elif qrs_pred[i]: current_class = 'green' elif t_pred[i]: current_class = 'purple' if current_class != prev_class: if prev_class is not None: ax1.axvspan(start_idx, i, color=prev_class, alpha=0.5) start_idx = i prev_class = current_class # Fill the last region if prev_class is not None: ax1.axvspan(start_idx, end, color=prev_class, alpha=0.5) # Plotting for ground truth prev_class = None start_idx = start for i in range(start, end): current_class = None if bl_true[i]: current_class = 'grey' elif p_true[i]: current_class = 'orange' elif qrs_true[i]: current_class = 'green' elif t_true[i]: current_class = 'purple' if current_class != prev_class: if prev_class is not None: ax2.axvspan(start_idx, i, color=prev_class, alpha=0.5) start_idx = i prev_class = current_class # Fill the last region if prev_class is not None: ax2.axvspan(start_idx, end, color=prev_class, alpha=0.5) # first row for prediction (X_unseen, y_pred) ax1.plot(Xt, color='blue') ax1.set_title('Prediction') # 修改2:隐藏上方子图的x轴刻度和标签,避免重叠 ax1.set_xticks([]) ax1.set_xticklabels([]) # second row for ground truth (X_unseen, y_true) ax2.plot(Xt, color='blue') ax2.set_title('Ground Truth') # 修改3:优化整体布局 plt.tight_layout() # plot plt.show()
内容的提问来源于stack exchange,提问作者Muhammad Ikhwan Perwira
相关产品推荐
相关产品推荐

