0

I have the following problem: I have a dataframe with a datetime index and columns that either contain float or boolean values, like this:

                     TAG_2552  TAG_2526
timestamp
2018-06-17 14:41:48      50.0      True
2018-06-17 14:41:49      51.0      True
2018-06-17 14:41:50      52.0      True
2018-06-17 14:41:51      49.0      True
2018-06-17 14:41:52      55.0      False
2018-06-17 14:41:53      50.0      False
2018-06-17 14:41:54      48.0      False
2018-06-17 14:41:55      54.0      False
2018-06-17 14:41:56      53.0      True
2018-06-17 14:41:57      50.0      True

I would like to plot this, which is not a problem for the float values. For the booleans, I would like to draw rectangles whenever they are True. I tried to use matplotlib.collections to do so .

I tried

df['datetime']=df.index
collection = collections.BrokenBarHCollection.span_where(df['datetime'].dt.date, ymin=0, ymax=1, where=df['TAG_2526']==True, facecolor='green', alpha=.5)

(and other variants) but this did not work.

It is possible to create a collection using

df['timedelta'] = df['datetime']-df['datetime'][0]
collection2 = collections.BrokenBarHCollection.span_where(myProc9['timedelta'].astype('timedelta64[ns]')/np.timedelta64(1,'s'), ymin=0, ymax=1, where=myProc9['TAG_2503']==True, facecolor='green', alpha=.5)

But as I would like to plot against the original datetime because I would like to share the x-Axis, so the only option I can see is to plot everything against myProc9['timedelta'].astype('timedelta64[ns]')/np.timedelta64(1,'s') and relabel the x-Axis.

I checked different pages about changing the datetime-format, but matplotlib.collections does not seem to take anything, the usual error message is

TypeError: float() argument must be a string or a number, not 'datetime.date'

(or whatever else I tried, for various conversions between datetime formats see here: Converting between datetime, Timestamp and datetime64)

I was wondering if there is a better way of doing this (not use matplotlib.collections) or a different way of calling it?

1 Answer 1

1

I was about to delete the question, but maybe it will be usefull for somebody sometime.

ax.fill_between(df.index, 0,1,where=df['TAG_2526'])

does the job and seems fairly generous regarding timestamps.

Link: https://matplotlib.org/gallery/pyplots/whats_new_98_4_fill_between.html#sphx-glr-gallery-pyplots-whats-new-98-4-fill-between-py

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.