You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用matplotlib的ax.fill填充绿色onset与粉色offset三角间背景?

解决Matplotlib中为Onset/Offset区间填充背景色的报错问题

我用Matplotlib绘制了运动数据图表,但内容繁杂,想给绿色三角(Datavyu Onset)和粉色三角(Datavyu Offset)标记的区间填充背景色。但运行代码时出现错误:

setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (4, 2) + inhomogeneous part.

原代码片段如下:

import pandas as pd
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, figsize=(20, 10), facecolor=(1, 1, 1))

ax.plot(df["Time"], Right_Elbow_Angles, label="Right Elbow Angle", color="gold",linewidth=5,)
ax.plot(df["Time"], SF_Right_Elbow_Angles,label="Right Elbow Angle",color="black",linewidth=5,)
ax.plot(df["Time"][onset_Angle],np_SF_Right_Elbow_Angle[onset_Angle],"bD",label="MediaPipe Onset",  markersize=15)
ax.plot(df["Time"][offset_Angle],np_SF_Right_Elbow_Angle[offset_Angle],"rd",label="MediaPipe Offset",    markersize=15)
ax.plot(df["Time"][onset], np_SF_Right_Elbow_Angle[onset],"g^",label="Datavyu Onset",markersize=15,)
ax.plot(df["Time"][offset], np_SF_Right_Elbow_Angle[offset],"mv",label="Datavyu Offset",markersize=15,)

# 报错的循环部分
for i in df["Time"][onset]:
    ax.axvspan(df["Time"][onset], df["Time"][offset], facecolor='b', alpha=0.5)

错误原因

报错核心是ax.axvspan需要单个的起始/结束时间值,但你在循环里传入了整个df["Time"][onset]和df["Time"][offset]数组,导致形状不匹配;同时循环遍历df["Time"][onset]的方式错误,应该遍历每一对对应的onset和offset索引。

解决方案

方法1:用ax.axvspan(推荐,简洁适配垂直区间)

假设onset和offset是长度相同的索引数组(每个onset对应一个offset),修改循环为遍历每一对时间点:

# 替换原来的循环
for start_idx, end_idx in zip(onset, offset):
    start_time = df["Time"].iloc[start_idx]
    end_time = df["Time"].iloc[end_idx]
    ax.axvspan(start_time, end_time, facecolor='b', alpha=0.5)

方法2:用ax.fill实现(自定义填充区域)

如果一定要用ax.fill,可以构造覆盖整个Y轴范围的矩形区域:

# 获取当前Y轴的上下限
y_min, y_max = ax.get_ylim()
for start_idx, end_idx in zip(onset, offset):
    start_time = df["Time"].iloc[start_idx]
    end_time = df["Time"].iloc[end_idx]
    # 构造填充坐标点:左下、左上、右上、右下
    ax.fill([start_time, start_time, end_time, end_time], 
            [y_min, y_max, y_max, y_min], 
            facecolor='b', alpha=0.5)
# 注意:若后续调整Y轴范围,需重新设置填充区域,建议先填充再调整轴参数

两种方法都能实现区间背景填充,ax.axvspan更简洁,自动适配Y轴范围;ax.fill更灵活,适合自定义填充形状。

内容的提问来源于stack exchange,提问作者Galaxy.Boy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:42:49