Python matplotlib 中的直方图,x 轴上的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29672375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Histogram in matplotlib, time on x-Axis
提问by Stophface
I am new to matplotlib (1.3.1-2) and I cannot find a decent place to start. I want to plot the distribution of points over time in a histogram with matplotlib.
我是 matplotlib (1.3.1-2) 的新手,我找不到合适的起点。我想用 matplotlib 在直方图中绘制点随时间的分布。
Basically I want to plot the cumulative sum of the occurrence of a date.
基本上我想绘制日期出现的累积总和。
date
2011-12-13
2011-12-13
2013-11-01
2013-11-01
2013-06-04
2013-06-04
2014-01-01
...
That would make
那会让
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
(i.e. 1 year steps) and finally decide how many bins
there will be.
由于很多年会有很多点,我想start date
在myx-Axis
和the上设置end date
,然后标记n-time steps
(即1年的步骤),最后决定bins
会有多少。
How would I achieve that?
我将如何实现这一目标?
采纳答案by hitzg
Matplotlib uses its own format for dates/times, but also provides simple functions to convert which are provided in the dates
module. It also provides various Locators
and Formatters
that take care of placing the ticks on the axis and formatting the corresponding labels. This should get you started:
Matplotlib 使用自己的日期/时间格式,但也提供了dates
模块中提供的简单函数来转换。它也提供了各种Locators
与Formatters
该照顾放置在轴上的蜱和格式化相应标签。这应该让你开始:
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()
Result:
结果:
回答by Will Vousden
To add to hitzg's answer, you can use AutoDateLocator
and AutoDateFormatter
to have matplotlib do the location and formatting for you:
要添加到 hitzg 的答案中,您可以使用AutoDateLocator
并AutoDateFormatter
让 matplotlib 为您执行位置和格式设置:
locator = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))