Reputation: 1199
I see countless examples through blogs and on this site (see posts like Modify date ticks for pandas plot) of being able to use matplotlib.dates
to control plotting of pandas
dataframe plotting. I am struggling to get similar behaviour:
import pandas as pd
import sys
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import ticker
print(f'System info: {sys.version}')
print(f'Pandas Version: {pd.__version__}')
print(f'Matplotlib Version: {matplotlib.__version__}')
index = pd.date_range(start='12/21/19 10:43:00', end='2019-12-21 10:47:00', freq= '10s')
data = {'A': [0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0.],
'B': [2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0.]}
df = pd.DataFrame(index=index, data=data)
ax = df.plot()
ax.xaxis.set_minor_locator(ticker.NullLocator())
ax.xaxis.set_major_locator(mdates.SecondLocator(interval=15))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.gcf().autofmt_xdate()
# ax.get_figure().canvas.draw()
plt.show()
The output of my terminal is:
System info: 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)]
Pandas Version: 0.25.3
Matplotlib Version: 3.1.2
I get no labels at all. It seems as though pandas
or matplotlib
isn't converting to datetime
, even though date_range
produces datetime
objects.
Upvotes: 0
Views: 1163
Reputation: 471
I don't think you asked this, but if you use matplotlib to plot instead of Pandas I get your expected result.
See my modifications to your code below,
import pandas as pd
import sys
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import ticker
print(f'System info: {sys.version}')
print(f'Pandas Version: {pd.__version__}')
print(f'Matplotlib Version: {matplotlib.__version__}')
index = pd.date_range(start='12/21/19 10:43:00', end='2019-12-21 10:47:00', freq= '10s')
data = {'A': [0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0.],
'B': [2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0.]}
df = pd.DataFrame(index=index, data=data)
#ax = df.plot()
Here I plot your data using matplotlib
fig, ax = plt.subplots()
ax.plot(df.index, df['A'])
ax.plot(df.index, df['B'])
ax.xaxis.set_minor_locator(ticker.NullLocator())
ax.xaxis.set_major_locator(mdates.SecondLocator(interval=15))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.gcf().autofmt_xdate()
# ax.get_figure().canvas.draw()
plt.show()
Upvotes: 1