Python 使用pyplot打印元组和字符串
我有一个带有时间戳和用户名的元组列表,我试图画出时间戳的频率图 这意味着x轴将从最早的时间戳到最晚的时间戳,y轴将显示一个时间段内的频率。我也在寻找一种方法来标记时间戳所连接的用户名图(使用不同的颜色等) 我在谷歌上搜索了几个小时,但找不到任何符合我所寻找的例子。这里有人能给我指一下正确的方向吗 时间戳是历元时间。例如:Python 使用pyplot打印元组和字符串,python,datetime,matplotlib,Python,Datetime,Matplotlib,我有一个带有时间戳和用户名的元组列表,我试图画出时间戳的频率图 这意味着x轴将从最早的时间戳到最晚的时间戳,y轴将显示一个时间段内的频率。我也在寻找一种方法来标记时间戳所连接的用户名图(使用不同的颜色等) 我在谷歌上搜索了几个小时,但找不到任何符合我所寻找的例子。这里有人能给我指一下正确的方向吗 时间戳是历元时间。例如: lst= [('john', '1446302675'), ('elvis', '1446300605'),('peter','1446300622'), ...] 谢谢您可
lst= [('john', '1446302675'), ('elvis', '1446300605'),('peter','1446300622'), ...]
谢谢您可以通过简单地计算每个日期的用户数来创建柱状图,然后用条形图显示:
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()
这导致:
有关创建条形图的更多详细信息,请参见[示例]
()
编辑1:使用您添加的数据格式,您可以使用以下方法转换时间戳来使用我的示例:
如果只想使用年-月日期,则可以使用:
>>> datetime.fromtimestamp(float('1446302675')).strftime('%Y-%m-%d')
'2015-10-31'
您可以通过简单地计算每个日期的用户数来创建柱状图,然后用条形图显示:
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()
这导致:
有关创建条形图的更多详细信息,请参见[示例]
()
编辑1:使用您添加的数据格式,您可以使用以下方法转换时间戳来使用我的示例:
如果只想使用年-月日期,则可以使用:
>>> datetime.fromtimestamp(float('1446302675')).strftime('%Y-%m-%d')
'2015-10-31'
你能添加一个示例元组吗?我刚刚添加了一个示例。你能添加一个示例元组吗?我刚刚添加了一个示例。