根据条件用python填充颜色

时间:2020-02-06 09:04:45

标签: python pandas matplotlib plotly

我用数据集df绘制了一个图,其中Timestamp是索引:

df

      Timestamp     Temperature     
2020-02-06 08:23:04 18.5    
2020-02-06 08:23:05 18.5    
2020-02-06 08:23:06 18.5    
2020-02-06 08:23:07 18.5    
2020-02-06 08:23:08 18.5    
... ... ...
2020-02-06 20:14:36 21.0    

和代码

df.plot( y='Temperature', figsize=(16, 10),) 
plt.axhline(y=40, color='r', linestyle='-')
plt.axhline(y=25, color='b', linestyle='-')
plt.show()

图形如下:

enter image description here

我想为温度在 25°C和40°C(在三角形内)之间的区域填充颜色。我可以通过调整代码来做到这一点吗?如果没有,执行此操作的好方法是什么?谢谢!

注意:数据不是连续的,但已向前填充以具有1秒的恒定间隔。同样,峰值温度高于40°C,Timestamp中相应的垂直部分不应着色。

1 个答案:

答案 0 :(得分:2)

我可以使用fill_between参数使用where来建议这种方法:

Timestamp = pd.date_range('2020-02-06 08:23:04', periods=1000, freq='s')
df = pd.DataFrame({'Timestamp': Timestamp,
                   'Temperature': 30+15*np.cos(np.linspace(0,10,Timestamp.size))})

df['top_lim'] = 40.
df['bottom_lim'] = 25.

plt.plot_date(df['Timestamp'], df['Temperature'], '-')
plt.plot_date(df['Timestamp'], df['top_lim'], '-', color='r')
plt.plot_date(df['Timestamp'], df['bottom_lim'], '-', color='blue')

plt.fill_between(df['Timestamp'], df['bottom_lim'], df['Temperature'],
                where=(df['Temperature'] >= df['bottom_lim'])&(df['Temperature'] <= df['top_lim']),
                facecolor='orange', alpha=0.3)

########### EDIT ################

# plt.fill_between(df['Timestamp'], df['bottom_lim'], df['top_lim'],
#                 where=(df['Temperature'] >= df['top_lim']),
#                 facecolor='orange', alpha=0.3)


mask = (df['Temperature'] <= df['top_lim'])&(df['Temperature'] >= df['bottom_lim'])
plt.scatter(df['Timestamp'][mask], df['Temperature'][mask], marker='.', color='black')
cumulated_time = df['Timestamp'][mask].diff().sum()
plt.title(f'Cumulated time in range = {cumulated_time}')
plt.show()

enter image description here