Search code examples
pythonpandasmatplotlibconditional-statementsfill

Matplotlib plot Pandas df, fill between index values if condition


I have a Pandas df:

           ro laws  ro ordos  
January        468       579     
February       216       231     
March         1005       276      
April         1044       250     
May            962       276       
June           999       568      
July          1360       298      
August          56       934      
September      202       289       
October        901       324       
November      1056       412       
December      1121       525

I plot it using matplotlib and it works as expected. I want to fill between the two lines but only when x axis is 'January', 'February', 'March'.

I tried:

ax.fill_between(plotMonths.index, plotMonths['ro laws'], plotMonths['ro ordos'], where=(plotMonths.index in ['January', "February", 'March']),
                       facecolor='lightskyblue', 
                       alpha=0.2)

but it throws the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried:

d = plotMonths.index.values.tolist() 
ax.fill_between(d, plotMonths['ro laws'], plotMonths['ro ordos'], where=(d in ['January', "February", 'March']),
                       facecolor='lightskyblue', 
                       alpha=0.2)

but it does nothing, the plot is un-filled.

How can I fix this?

Thank you. enter image description here


Solution

  • Python in keyword checks for an element in a iterable, but you are using it to check if an array (plotMonths.index) is in a iterable ['January', "February", 'March'].
    The proper way to vectorize the conditional is to use the built in method .isin().
    So, you should use:

    ax.fill_between(x = plotMonths.index,
                    y1 = plotMonths['ro laws'],
                    y2 = plotMonths['ro ordos'],
                    where = plotMonths.index.isin(['January', "February", 'March']),
                    facecolor = 'lightskyblue',
                    alpha = 0.2)
    

    enter image description here