如何读取.txt文件以绘制图形
我有一个.txt文件,每15秒就会更新一次,里面会添加新的数据,格式如下:
13:57:06,389,492,140
13:57:21,139,181,484
13:57:36,483,294,414
13:57:51,373,382,195
13:58:06,425,360,277
13:58:21,394,310,307
13:58:36,327,291,303
13:58:52,461,352,133
13:59:07,242,426,492
13:59:22,389,448,296
13:59:37,301,443,366
13:59:52,212,229,106
14:02:08,112,442,347
14:02:23,284,361,329
14:02:39,353,438,467
14:02:54,254,385,401
14:03:09,217,125,410
14:03:24,295,266,326
14:03:39,389,209,196
14:03:54,323,203,147
14:04:10,346,230,365
14:04:25,143,181,261
14:04:40,294,104,230
14:04:55,376,264,357
每一行包含一个时间戳,后面跟着三个数字,这些数字是来自PLC(可编程逻辑控制器)的读数。我想把这些值画成图,显示三条曲线,分别代表每组读数随时间的变化。
不过,当我尝试用pandas读取这个.txt文件时,遇到了一些困难。看起来我的方法可能不太适合处理.txt文件,因为我对pandas处理CSV文件比较熟悉。有没有人能指导我,怎么正确地把这些数据读入到一个DataFrame中,分开这些数值,并创建一个包含三条曲线的图?
1 个回答
2
试试这个:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("your_file.txt", header=None) # header=None <-- assuming you have no header row
df.columns = ["time", "col1", "col2", "col3"] # give names to columns
plt.plot(df["time"], df["col1"], label="Col 1")
plt.plot(df["time"], df["col2"], label="Col 2")
plt.plot(df["time"], df["col3"], label="Col 3")
plt.xlabel("Time")
plt.ylabel("Value")
plt.title("My Graph")
plt.xticks(rotation=45)
plt.legend()
plt.show()
这样会生成这个图表:
或者柱状图:
# ...
bar_width = 0.25
index = np.arange(len(df))
plt.bar(index, df["col1"], bar_width, label="Col 1")
plt.bar(index + bar_width, df["col2"], bar_width, label="Col 2")
plt.bar(index + 2 * bar_width, df["col3"], bar_width, label="Col 3")
plt.xticks(index + bar_width, df["time"], rotation=45)
# ...
会生成这个图表: