[英]How can I order the table by month and then show it in plot chart? Python
[英]How can i plot line chart in python?
我有一個txt文件 。 以下是一些示例行:
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
我想繪制這樣的折線圖:
我怎樣才能做到這一點?
我嘗試這個例子 ,但是我沒有做
plt.bar()
plt.xticks()
plt.ylabel()
plt.title()
plt.savefig()
plt.show()
我該如何開發此代碼?
您可以使用熊貓進行解析。 也許您可以研究pandas的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()
這是使用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軸上的時間戳,在matplotlib中顯示unix時間戳
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.