matplotlib 中的直方图,x 轴上的时间

新手上路,请多包涵

我是 matplotlib (1.3.1-2) 的新手,我找不到合适的起点。我想用 matplotlib 在直方图中绘制点随时间的分布。

基本上我想绘制日期出现的累计总和。

 date
2011-12-13
2011-12-13
2013-11-01
2013-11-01
2013-06-04
2013-06-04
2014-01-01
...

那将使

2011-12-13 -> 2 times
2013-11-01 -> 3 times
2013-06-04 -> 2 times
2014-01-01 -> once

Since there will be many points over many years, I want to set the start date on my x-Axis and the end date , and then mark n-time steps (即 1 年步骤)并最终决定将有多少 bins

我将如何实现这一目标?

原文由 four-eyes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 624
2 个回答

Matplotlib 使用自己的日期/时间格式,但也提供简单的转换函数,这些函数在 dates 模块中提供。它还提供各种 LocatorsFormatters 负责将刻度放置在轴上并格式化相应的标签。这应该让你开始:

 import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# generate some random data (approximately over 5 years)
data = [float(random.randint(1271517521, 1429197513)) for _ in range(1000)]

# convert the epoch format to matplotlib date format
mpl_data = mdates.epoch2num(data)

# plot it
fig, ax = plt.subplots(1,1)
ax.hist(mpl_data, bins=50, color='lightblue')
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
plt.show()

结果:

在此处输入图像描述

原文由 hitzg 发布,翻译遵循 CC BY-SA 3.0 许可协议

要添加到 hitzg 的答案,您可以使用 AutoDateLocatorAutoDateFormatter 让 matplotlib 为您进行位置和格式设置:

 locator = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))

在此处输入图像描述

原文由 Will Vousden 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题