Search code examples
pythonmatplotlibplot

using ax.fill to fill between x slots


I have plotted my data by matplotlib but it is busy and confusing to extract the information. I would like to change the background colour for the distance between green (onset) and pink (offset) triangles.

I used the below commands for the current plot. But it shows this error:

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.

How can I use the ax.fill command for my work?

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)

enter image description here


Solution

  • Assuming the length of df["Time"][onset] and df["Time"][offset] are the same, you could loop over both of those with zip, and use those for the xmin and xmax in axvspan.

    for i, j in zip(df["Time"][onset], df["Time"][offset]):
        ax.axvspan(i, j, facecolor='b', alpha=0.5)