我一直想在 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 轴上显示日期滚动条?
最佳答案
在绘图上使用 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()
在轴上添加了一些养眼的东西。结果如下。
关于python - 如何在 Python 中打印日期滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065116/