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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:52:15  来源:igfitidea点击:

Histogram in matplotlib, time on x-Axis

pythontimematplotlibplothistogram

提问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 dateon my x-Axisand the end date, and then mark n-time steps(i.e. 1 year steps) and finally decide how many binsthere 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 datesmodule. It also provides various Locatorsand Formattersthat take care of placing the ticks on the axis and formatting the corresponding labels. This should get you started:

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

Result:

结果:

enter image description here

在此处输入图片说明

回答by Will Vousden

To add to hitzg's answer, you can use AutoDateLocatorand AutoDateFormatterto have matplotlib do the location and formatting for you:

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

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

enter image description here

在此处输入图片说明