2009-10-15 103 views
88

我有一个格式为(HH:MM:SS.mmmmmm)的时间戳数组和另一个浮点数数组,每个数组对应于timestamp数组中的一个值。使用Matplotlib绘制Python的时间

我可以使用Matplotlib绘制x轴上的时间和y轴上的数字吗?

我正在尝试,但不知何故它只接受浮点数组。我怎样才能得到它的时间?我需要以任何方式修改格式吗?

回答

107

您必须先将时间戳转换为Python datetime对象(使用datetime.strptime)。然后使用date2num将日期转换为matplotlib格式。

叠加使用plot_date日期和值:

dates = matplotlib.dates.date2num(list_of_datetimes) 
matplotlib.pyplot.plot_date(dates, values) 
+1

它会绘制日期还是只是时间?我只想把时间转换为日期时间,年份设置为1990. – randomThought

+0

“...转换为日期时间,年份设置为1990”:您可以发布您用于从字符串转换为日期时间的代码?转换可能有问题。回覆。图表标签的格式,请参阅由J. K.Seppänen提供的date_demo1链接。 matplot lib文档非常好,顺便说一下。 http://matplotlib.sourceforge.net/index.html – codeape

+11

plot_dates - > matplotlib.pyplot.plot_date(日期,值) – Pete

52

您也可以使用pyplot.plot(从他们的字符串表示它们解析后)绘制的时间戳,值对。 (测试与matplotlib版本1.2.0和1.3.1。)

实施例:

import datetime 
import random 
import matplotlib.pyplot as plt 

# make up some data 
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)] 
y = [i+random.gauss(0,1) for i,_ in enumerate(x)] 

# plot 
plt.plot(x,y) 
# beautify the x-labels 
plt.gcf().autofmt_xdate() 

plt.show() 

得到的图像:

Line Plot


下面是相同的散点图:

import datetime 
import random 
import matplotlib.pyplot as plt 

# make up some data 
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)] 
y = [i+random.gauss(0,1) for i,_ in enumerate(x)] 

# plot 
plt.scatter(x,y) 
# beautify the x-labels 
plt.gcf().autofmt_xdate() 

plt.show() 

生成类似这样的图像:

Scatter Plot

+2

如何让它工作散点图? – andi

+4

@andi它应该像我的例子一样工作(将'plot'更改为'scatter')。 – moooeeeep

+1

我不明白为什么这是我遇到过的第五个问题,其中没有人真正使用散点图进行* TRIED * - 它不起作用。 '类型错误 - 无效类型提升'。 – dwanderson

2

7年后,这代码已经帮助了我。 但是,我的时代仍然没有正确显示。

enter image description here

使用Matplotlib 2.0.0,我不得不从Editing the date formatting of x-axis tick labels in matplotlib由Paul H.

import matplotlib.dates as mdates 
myFmt = mdates.DateFormatter('%d') 
ax.xaxis.set_major_formatter(myFmt) 

添加以下代码位,我改变了格式(%H:%M)和时间显示正确。 enter image description here

都感谢社区。

1

我在使用matplotlib版本:2.0.2时遇到了麻烦。从上面运行示例,我得到了一组居中堆叠的气泡。如所期望

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


# make up some data 
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)] 
y = [i+random.gauss(0,1) for i,_ in enumerate(x)] 

# plot 
plt.plot([],[]) 
plt.scatter(x,y) 

# beautify the x-labels 
plt.gcf().autofmt_xdate() 
myFmt = mdates.DateFormatter('%H:%M') 
plt.gca().xaxis.set_major_formatter(myFmt) 

plt.show() 
plt.close() 

这产生具有分布式气泡的图像:

plt.plot([],[]) 

的完整代码段变为:

graph with centered stack of bubbles

我通过添加另一行的 “固定” 的问题。

graph with bubbles distributed over time

+0

感谢您的更新版本。 – Aventinus