python中x轴上带有日期时间的绘图中的阴影区域(axhspan,matplotlib) [英] Shade area in plot with datetime on xaxis (axhspan, matplotlib) in python

查看:186
本文介绍了python中x轴上带有日期时间的绘图中的阴影区域(axhspan,matplotlib)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的pd df,每列大约有6000个条目:

I have a pd df like that with around 6000 entries per column:

                  datetime      value  flag        date
0      2015-01-01 07:00:00   0.018013   0.0  2015-01-01
1      2015-01-01 07:06:00   0.101957   1.0  2015-01-01
2      2015-01-01 07:12:00   0.141712   1.0  2015-01-01
3      2015-01-01 07:18:00   0.178875   0.0  2015-01-01
4      2015-01-01 07:24:00   0.237765   0.0  2015-01-01
                       ...        ...   ...         ...

现在,我想在x轴上绘制日期时间,在y轴上绘制值,并在标记= 0时阴影区域.,而不是一条线(使用axvline可以)但整个6分钟,直到下一次测量.而且我想每天创建一个绘图,这就是为什么它以for循环开头的原因.

Now I want to plot the datetime on the x-axis and the value on the y-axis and shade the area when the flag = 0. but not a line (with axvline it works) but the whole 6 minutes until the next measurement. And I want to create one plot per day, that is why it starts with a for loop.

我尝试过这样的事情:

import pandas as pd
import matplotlib.pyplot as plt

for date in df.date.unique():
    fig, ax = plt.subplots(nrows=1, ncols=1)
    ax.plot('datetime', 'value', data=df[df.date == date])
    for flags in df[(df.date == date) & (df.flag == 0.)].datetime:
        ax.axhspan(flags, flags+pd.Timedelta(minutes=6), facecolor='0.5', alpha=0.5)

当我尝试这个时,即使 flagsflags+pd.Timedelta(minutes=6)df 中的条目,我也会收到以下错误.datetime 的类型为:pandas._libs.tslibs.timestamps.Timestamp

When I try this, I get the following error even though the flags, flags+pd.Timedelta(minutes=6) and the entries in df.datetime have the type: pandas._libs.tslibs.timestamps.Timestamp

ValueError: view limit minimum -36835.18135207975 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

有人知道它是如何工作的吗?提前致谢!

Does anyone have any idea how it could work? Thanks in advance!

推荐答案

我是这样想出来的:不幸的是我使用了错误的命令,我必须使用 axvspan 而不是 axhspan.绘图与:

I figured it out this way: Unfortunately I used the wrong command, I have to use axvspan instead of axhspan. The plotting worked with:

ax.axvspan(mdates.date2num(flags), mdates.date2num(flags+pd.Timedelta(minutes=6)), facecolor='0.5', alpha=0.5)

这篇关于python中x轴上带有日期时间的绘图中的阴影区域(axhspan,matplotlib)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆