python - 如何在 Python 中打印日期滚动条

标签 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 轴上显示日期滚动条?

最佳答案

在绘图上使用 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

关于python - 如何在 Python 中打印日期滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065116/

相关文章:

python - 计算适合 Tkinter 中列表框可视区域的项目数量

python - 普朗克定律,频率数字

python - 使用 matplotlib 将 RGBA 元组转换为十六进制

python - 我不明白为什么一个代码有效而另一个代码无效

python - 为什么 min({1},{0}) 返回 {1}

python - 删除所有 XML 标签,只保留标签之间的文本

Python 3 包模块与标准模块冲突

python - O(log n) 在排序的 python 字典中搜索

python - 如何将抖动添加到具有 X 和 Y 值的散点图?

python - 在 Pandas 中使用特定的图形处理程序