我怎么能在python中绘制折线图?

时间:2015-12-08 15:28:56

标签: python matplotlib plot linechart

我有txt file 。以下是一些示例行:

getElement().getStyle().setProperty("opacity", "1");
getElement().getStyle().setProperty("pointerEvents", "");

我想像这样绘制折线图:

like this

我该怎么做?

我尝试this example,但我没有这样做

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

我怎么能开发这段代码?

2 个答案:

答案 0 :(得分:3)

您可以使用pandas进行解析。也许您可以查看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()

enter image description here

答案 1 :(得分: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

Graphs Image