如何在Python中打印日期自动收报机

时间:2014-11-21 15:45:16

标签: python matplotlib

我的意思是在matplotlib中将日期作为我的x轴进行绘图,但我得到了以下的浮动值。

我的代码如下:

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()

问题:如何在x轴上显示日期代码?

2 个答案:

答案 0 :(得分:1)

在图上使用data_time.to_pydatetime()以防止MatPlotLib将日期范围转换为浮点值。请参阅下面的代码。

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()

为轴添加了一些眼睛。结果如下。

enter image description here

答案 1 :(得分:1)

使用Metatron数据的更简化的解决方案

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()

enter image description here