matplotlib 中的直方图,x 轴上的时间 [英] Histogram in matplotlib, time on x-Axis

查看:31
本文介绍了matplotlib 中的直方图,x 轴上的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

基本上我想绘制日期出现的累积总和.

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
...

那会让

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

因为很多年会有很多点,所以我想在我的x-Axisend date上设置start date,然后标记n-time steps(即1年的steps),最后决定有多少bins.

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.

我将如何实现这一目标?

How would I achieve that?

推荐答案

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

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:

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

结果:

这篇关于matplotlib 中的直方图,x 轴上的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆