【问题标题】:Plot tuple and string using pyplot使用 pyplot 绘制元组和字符串
【发布时间】:2015-10-31 20:30:50
【问题描述】:

我有带有时间戳和用户名的元组列表,我正在尝试绘制时间戳的频率图。

这意味着 x 轴将是从最早的时间戳到最新的时间戳,y 轴将显示一个时间段内的频率。我也在寻找方法来标记时间戳连接到的用户名图(使用不同的颜色等)。

我已经在谷歌上搜索了几个小时,但找不到任何符合我要求的示例。这里有人能指出我正确的方向吗?

时间戳是纪元时间。示例:

lst= [('john', '1446302675'), ('elvis', '1446300605'),('peter','1446300622'), ...]

谢谢

【问题讨论】:

  • 你能添加一个示例元组吗?
  • 我刚刚添加了一个例子。

标签: python datetime matplotlib


【解决方案1】:

您可以通过简单地计算每个日期的用户数来创建直方图,然后用条形图显示它:

import numpy as np
import matplotlib.pyplot as plt    

# some data
data=[('2013-05-15','test'),('2013-05-16','test'),('2013-05-14','user2'),('2013-05-14', 'user')]

# to create the histogram I use a dict()
hist = dict()
for x in data:
   if x[0] in hist:
     hist[x[0]] += 1
   else:
     hist[x[0]] = 1

# extract the labels and sort them
labels = [x for x in hist]
labels = sorted(labels)
# extract the values
values = [hist[x] for x in labels]
num = len(labels)

# now plot the values as bar chart
fig, ax = plt.subplots()
barwidth = 0.3
ax.bar(np.arange(num),values,barwidth)
ax.set_xticks(np.arange(num)+barwidth/2)
ax.set_xticklabels(labels)
plt.show()

这会导致:

有关创建条形图的更多详细信息,请参阅 [示例] (http://matplotlib.org/examples/api/barchart_demo.html)。

编辑 1:使用您添加的数据格式,您可以使用我的示例,通过使用 this 方法转换时间戳:

>>> from datetime import datetime
>>> datetime.fromtimestamp(float('1446302675')).strftime('%Y-%m-%d %H:%M:%S')
'2015-10-31 15:44:35'

如果你只想使用年-月-日,那么你可以使用:

>>> datetime.fromtimestamp(float('1446302675')).strftime('%Y-%m-%d')
'2015-10-31'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多