我用数据集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()
图形如下:
我想为温度在 25°C和40°C(在三角形内)之间的区域填充颜色。我可以通过调整代码来做到这一点吗?如果没有,执行此操作的好方法是什么?谢谢!
注意:数据不是连续的,但已向前填充以具有1秒的恒定间隔。同样,峰值温度高于40°C,Timestamp
中相应的垂直部分不应着色。
答案 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()