2015-12-08 47 views
-2

我有一個txt file。下面是一些例子行:我怎樣才能在python中繪製折線圖?

computer 2015-11-26 08:47:00 86 
computer 2015-11-26 08:48:00 78 
computer 2015-11-26 08:49:00 61 
computer 2015-11-26 08:50:00 50 
computer 2015-11-26 08:51:00 53 
computer 2015-11-26 08:52:00 61 
computer 2015-11-26 08:53:00 60 
computer 2015-11-26 08:54:00 50 
computer 2015-11-26 08:55:00 91 
computer 2015-11-26 08:56:00 99 
computer 2015-11-26 08:57:00 75 
computer 2015-11-26 08:58:00 105 
computer 2015-11-26 08:59:00 67 
computer 2015-11-26 09:00:00 63 

我想繪製折線圖是這樣的:

like this

我怎麼能做到這一點?

我嘗試this example,但我沒有做到這一點

plt.bar() 
     plt.xticks() 
     plt.ylabel() 
     plt.title() 
     plt.savefig() 
     plt.show() 

我怎麼能發展Deng這個代碼?

回答

3

您可以使用熊貓進行解析。也許你可以看看大熊貓GROUPBY功能,使代碼更優秀,但是這是一個工作示例(Python 3.X)

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.read_csv('t.txt', delim_whitespace=True, header=None, parse_dates={'Dates': [1, 2]}) 

plt.figure() 
l_h = [] 
for identifier in df[0].unique(): 
    h, = plt.plot(df[df[0]==identifier]['Dates'], df[df[0]==identifier][3], label=identifier) 
    l_h.append(h) 
plt.legend(handles=l_h) 
plt.show() 

enter image description here

+0

我必須使用python 2.7 – Nicqu

+0

這段代碼也適用於python 2.7。剛剛檢查過它...您必須安裝matplotlib和pandas,您可以從導入語句中看到... – Maecky

+0

我安裝了熊貓圖書館及其工作感謝:) – Nicqu

0

這是使用matplotlib完成:

import matplotlib.dates as md 
import datetime as dt 
import matplotlib.pyplot as plt 
import numpy as np 
import re 

computerData =[] 
studentData = [] 
universityData = [] 
scienceData = [] 
timestamp1 = [] 
timestamp2 = [] 
timestamp3 = [] 
p = re.compile("^.*[a-z]. ([0-9].*) ([0-9]*)$") 
f = open(r"t.txt") 
for line in f: 
    if line.startswith("computer"): 
     t1 = p.search(line) 
     dates1 = dt.datetime.strptime(t1.group(1), "%Y-%m-%d %H:%M:%S") 
     time1 = md.date2num(dates1) 
     timestamp1.append(time1) 
     computerData.append(int(t1.group(2))) 

    if line.startswith("student"): 
     t2 = p.search(line) 
     dates2 = dt.datetime.strptime(t2.group(1), "%Y-%m-%d %H:%M:%S") 
     time2 = md.date2num(dates2) 
     timestamp2.append(time2) 
     studentData.append(int(t2.group(2))) 

    if line.startswith("science"): 
     t3 = p.search(line) 
     dates3 = dt.datetime.strptime(t3.group(1), "%Y-%m-%d %H:%M:%S") 
     time3 = md.date2num(dates3) 
     timestamp3.append(time3) 
     scienceData.append(int(t3.group(2))) 

ax=plt.gca() 
xfmt = md.DateFormatter('%H:%M') 
ax.xaxis.set_major_formatter(xfmt) 

plt.plot(timestamp1,computerData,'r', label="Computer", linewidth=2) 
plt.plot(timestamp2,studentData,'g', label="Student", linewidth=2) 
plt.plot(timestamp3,scienceData,'y', label="Science", linewidth=2) 

plt.legend() 
plt.grid(True,color='k') 
plt.show() 

參考: 要顯示在x軸上 plotting unix timestamps in matplotlib

時間戳