Reputation: 11
I've been meaning to plot with dates as my x-axis in matplotlib
but I'm getting the following float values instead.
My code is below:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
data_time=pd.date_range(start=datetime.datetime(2011, 1, 1, 0, 0, 0), periods=n, freq='H')
f,(ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(data_time, x['count'])
ax1.set_title('Date vs. Count')
percentage = x['registered']/x['count']
ax2.plot(data_time, percentage)
ax2.set_title('Date vs. Percentage of Registration')
ax2.xaxis_date(tz=None)
f.set_size_inches(15,10)
plt.show()
Question: How can I show the date tickers in the x-axis?
Upvotes: 1
Views: 504
Reputation: 2365
Just more simplified solution using Metatron's data
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data_time=pd.date_range(start="2011-01-01", periods=100, freq='D')
s1 = pd.Series(np.random.randint(80,100,100))
s2 = pd.Series(np.random.randint(60,70,100))
x = pd.concat([s1,s2], axis=1)
x.set_index(data_time, inplace=True)
x.columns = ['count','registered']
f,(ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(data_time.to_pydatetime(), x['count'])
ax1.set_title('Date vs. Count')
percentage = x['registered']/x['count']
ax2.plot(data_time.to_pydatetime(), percentage)
ax2.set_title('Date vs. Percentage of Registration')
f.autofmt_xdate(rotation=90) # auto formats dateobject and rotates it by given value
plt.show()
Upvotes: 1
Reputation: 14169
Use data_time.to_pydatetime()
on your plots to prevent MatPlotLib from converting the date range to a float values. See code below.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np
import pandas as pd
data_time=pd.date_range(start=datetime.datetime(2011, 1, 1, 0, 0, 0), periods=100, freq='D')
s1 = pd.Series(np.random.randint(80,100,100))
s2 = pd.Series(np.random.randint(60,70,100))
x = pd.concat([s1,s2], axis=1)
x.set_index(data_time, inplace=True)
x.columns = ['count','registered']
f,(ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(data_time.to_pydatetime(), x['count'])
ax1.set_title('Date vs. Count')
# Prettify the axes.
ax1.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(6),interval=1))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter('%d\n%a'))
ax1.xaxis.set_major_locator(mdates.MonthLocator())
ax1.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%b\n%Y'))
ax1.xaxis.grid(True, which="minor")
ax1.yaxis.grid()
percentage = x['registered']/x['count']
ax2.plot(data_time.to_pydatetime(), percentage)
ax2.set_title('Date vs. Percentage of Registration')
ax2.xaxis_date(tz=None)
ax2.xaxis.grid(True, which="minor")
ax2.yaxis.grid()
f.set_size_inches(15,10)
plt.show()
Added some eye-candy to the axes. Result as follows.
Upvotes: 1