Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When plotting datetime index data, put markers in the plot on specific days (e.g. weekend)

I create a pandas dataframe with a DatetimeIndex like so:

import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# create datetime index and random data column
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=14, freq='D')
data = np.random.randint(1, 10, size=14)
columns = ['A']

df = pd.DataFrame(data, index=index, columns=columns)

# initialize new weekend column, then set all values to 'yes' where the index corresponds to a weekend day
df['weekend'] = 'no'
df.loc[(df.index.weekday == 5) | (df.index.weekday == 6), 'weekend'] = 'yes'

print(df)

Which gives

            A weekend
2014-10-13  7      no
2014-10-14  6      no
2014-10-15  7      no
2014-10-16  9      no
2014-10-17  4      no
2014-10-18  6     yes
2014-10-19  4     yes
2014-10-20  7      no
2014-10-21  8      no
2014-10-22  8      no
2014-10-23  1      no
2014-10-24  4      no
2014-10-25  3     yes
2014-10-26  8     yes

I can easily plot the A colum with pandas by doing:

df.plot()
plt.show()

which plots a line of the A column but leaves out the weekend column as it does not hold numerical data.

Plot of 'A' but not of 'weekend'

How can I put a "marker" on each spot of the A column where the weekend column has the value yes?

like image 887
Dirk Avatar asked Oct 23 '14 12:10

Dirk


1 Answers

Meanwhile I found out, it is as simple as using boolean indexing in pandas. Doing the plot directly with pyplot instead of pandas' own plot wrapper (which is more convenient to me):

plt.plot(df.index, df.A)
plt.plot(df[df.weekend=='yes'].index, df[df.weekend=='yes'].A, 'ro')

Plot of 'A' with weekend markers

Now, the red dots mark all weekend days which are given by df.weekend='yes' values.

like image 96
Dirk Avatar answered Sep 29 '22 12:09

Dirk