【问题标题】:Colour fill on plot based on conditions with python根据python条件在绘图上填充颜色
【发布时间】:2020-05-22 06:36:25
【问题描述】:

我用数据集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 中的相应垂直部分不应着色。

【问题讨论】:

  • 如果你能发布你的整个数据集来帮助人们提供一个完整的例子:)
  • 嗨@CDJB 感谢您的评论,但我担心完整的数据集太大而无法在此处发布..
  • 这与情节有什么关系?

标签: python pandas matplotlib plotly


【解决方案1】:

我可以使用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()

【讨论】:

  • 您好 Andrea,感谢您的解决方案。是否可以排除曲线超过 40 的部分?因为我要计算温度在25到40之间的累计时间
  • 我不确定我明白了你的要求。编辑是否回答了您的问题?
  • 是的,这正是我想要的!只是一个问题,有没有办法替换.diff?由于Timestamp 列是index 格式,它返回AttributeError: 'DatetimeIndex' object has no attribute 'diff'
  • Here's 答案:)
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2015-04-04
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多