简体   繁体   中英

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. 在此处输入图片说明

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)

在此处输入图片说明

Just slice your data. For instance first three months = [0:3], like this:

import matplotlib.pyplot as plt
ax.plot(plotMonths.index, plotMonths['ro laws'])
ax.plot(plotMonths.index, plotMonths['ro ordos'])
ax.fill_between(plotMonths.index[0:3], plotMonths['ro laws'][0:3])
ax.fill_between(plotMonths.index[0:3], plotMonths['ro ordos'][0:3])
plt.show()

And it will fill just the subset you want. Here is an image with the outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM