简体   繁体   中英

Plot tuple and string using pyplot

I've got list of tuples with timestamps and usernames and I'm trying to make a plot of the frequency of the timestamps.

That means the x-axis will be from the earliest timestamp to the latest, y-axis will show the frequency within a time period. I'm also looking for way to mark the plots of username the timestamp is connected to (with different colors etc.).

I've been googling for hours, but can't find any examples that does what I'm looking for. Could anyone here point me in the right direction?

The timestamp is epoch time. Example:

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

Thanks

You could create the histogram by simply counting the users per date, and then show it with a bar chart:

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

This results in:

结果图

For more details on creating a bar chart see [an example] ( http://matplotlib.org/examples/api/barchart_demo.html ).

Edit 1 : with the data format you added you can use my example by converting the timestamp using this method:

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

If you only want to use year-month-date, then you can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM