umat
umat

Reputation: 715

Cannot set datetime ticks when using pandas

I am trying to plot some series with pandas. However I have a problem when I try to set major locator on axis with dates.

If you want to try on the same dataset as mine, here's the pickle.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_pickle('df.pkl')
df = df.set_index('time')

ax = df.plot(y=['dataset1', 'dataset2'], figsize=(10,5))

h_locator = mdates.HourLocator(byhour=[0, 6, 12, 18])
ax.xaxis.set_major_locator(h_locator)
ax.grid(True)
plt.show()

I want to display 4 grid ticks per day (hours: 0, 6, 12 and 18) but the output is the same as if I would not set any locator.

plot

My DataFrame looks like this:

                     dataset1  dataset2
2018-04-16 00:00:00  0.000000  0.516667
2018-04-16 00:15:00  0.011111  0.244444
2018-04-16 00:30:00  0.000000  0.388889
2018-04-16 00:45:00  0.000000  0.211111
2018-04-16 01:00:00  0.000000  0.127778
                       ...       ...
2018-04-19 22:45:00  0.022222  0.250000
2018-04-19 23:00:00  0.166667  0.505556
2018-04-19 23:15:00  0.000000  0.688889
2018-04-19 23:30:00  0.000000  1.733333
2018-04-19 23:45:00  0.055556  0.283333
[384 rows x 2 columns]

Upvotes: 0

Views: 126

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

In case you want to use the matplotlib.dates locators and formatters on a plot generated by pandas, you need to plot in compatibility mode,

df.plot(..., x_compat=True)

Upvotes: 3

Related Questions