如何基于时间序列值对matplotlib轴面的部分进行着色

ne5o7dgx  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(123)

给定具有时间序列的数据和与时间序列相关联的值,我想根据时间序列的值来对轴图的背景进行阴影处理,以便突出显示与时间相关的具有特定含义的值(例如-可能是季节,或开放时间等)。
我真的不知道如何做到这一点-但有一个图片的排序的事情,我的意思是:

我不太使用时间序列,但我试图创建一个适合示例数据的数据集:

import io

so_data = pd.read_csv(
    io.StringIO(
        "x,y,plt_mask\n2023-03-22 02:29:51,0.0,False\n2023-03-22 03:20:26,0.0,False\n2023-03-23 00:51:06,0.0,False\n2023-03-23 01:29:42,0.0,False\n2023-03-23 04:48:22,23.081085,False\n2023-03-23 07:13:11,50.0,True\n2023-03-23 08:46:27,50.0,True\n2023-03-23 12:34:13,0.0,False\n2023-03-23 12:46:35,0.0,False\n2023-03-23 16:02:13,0.0,False\n2023-03-23 17:58:47,0.0,False\n2023-03-23 18:34:27,0.0,False\n2023-03-23 20:28:29,1.0,False\n2023-03-24 05:25:20,0.0,True\n2023-03-24 09:03:36,0.0,True\n2023-03-24 09:06:09,0.0,True\n2023-03-24 10:53:44,70.0,True\n2023-03-24 13:10:03,1273.676636,False\n2023-03-24 17:03:16,21.0,False\n2023-03-24 18:22:23,1.0,False\n"
    )
)

fig, ax = plt.subplots()
so_data

fig.autofmt_xdate()

xfmt = matplotlib.dates.DateFormatter("%d-%m-%y %H:%M")
ax.xaxis.set_major_formatter(xfmt)

ax.plot(so_data["x"], so_data["y"])

这里,当plt_mask值为True时,轴背景应该是不同的颜色(绿色/其他)。

ffx8fchx

ffx8fchx1#

下面是一种可能的方法,使用您提供的示例pandas和ax.fill_betweenx(doc here):

import matplotlib.pyplot as plt
import matplotlib
import io
import pandas as pd

so_data = pd.read_csv(
    io.StringIO(
        "x,y,plt_mask\n2023-03-22 02:29:51,0.0,False\n2023-03-22 03:20:26,0.0,False\n2023-03-23 00:51:06,0.0,False\n2023-03-23 01:29:42,0.0,False\n2023-03-23 04:48:22,23.081085,False\n2023-03-23 07:13:11,50.0,True\n2023-03-23 08:46:27,50.0,True\n2023-03-23 12:34:13,0.0,False\n2023-03-23 12:46:35,0.0,False\n2023-03-23 16:02:13,0.0,False\n2023-03-23 17:58:47,0.0,False\n2023-03-23 18:34:27,0.0,False\n2023-03-23 20:28:29,1.0,False\n2023-03-24 05:25:20,0.0,True\n2023-03-24 09:03:36,0.0,True\n2023-03-24 09:06:09,0.0,True\n2023-03-24 10:53:44,70.0,True\n2023-03-24 13:10:03,1273.676636,False\n2023-03-24 17:03:16,21.0,False\n2023-03-24 18:22:23,1.0,False\n"
    )
)
fig, ax = plt.subplots()
fig.autofmt_xdate()

df_mask_true=so_data.loc[so_data['plt_mask']==True] #create a dataframe from the rows with plt_mask==True

ax.plot(so_data["x"], so_data["y"])

[ax.fill_betweenx([so_data['y'].min(),so_data['y'].max()],x,so_data['x'].iloc[so_data.index[so_data['x']==x]+1],facecolor='k',alpha=0.4)  for x in df_mask_true['x']] #fill the background between x and x+1 with grey

相关问题