Shade area in plot with datetime on xaxis (axhspan, matplotlib) in python

依然范特西╮ 提交于 2021-01-29 18:44:46

问题


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
                       ...        ...   ...         ...

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.

I tried something like this:

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)

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!


回答1:


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)


来源:https://stackoverflow.com/questions/61288154/shade-area-in-plot-with-datetime-on-xaxis-axhspan-matplotlib-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!