如何读取 .txt 文件以绘制显示日复一日、甚至月复一日的图表

问题描述 投票:0回答:1

我得到了以下格式的文件:

00:01:28,102,103,103 20-03-2024
00:02:16,111,110,110
00:02:33,108,109,109
00:02:49,107,108,108
24 hours read....
23:58:54,111,112,112
23:59:11,109,110,110
23:59:47,115,116,117
00:00:04,115,116,116 21-03-2024
00:00:20,121,122,120
00:00:36,124,125,125
24 hours read...
23:59:02,115,115,116
23:59:19,114,114,114
23:59:51,113,114,115
00:00:07,113,114,115 22-03-2024
00:00:24,116,117,115
00:00:45,115,115,116
24 hours read
23:59:08,101,101,100
23:59:32,103,103,102
23:59:48,102,102,102
Next day 

简单的阅读,但正如你所看到的,我添加了日期(日期),当日期在 00:00:00 更改时开始...... 当我尝试用 pandas 绘制这个读数时,xtick 值,在这种情况下,小时标签被剪裁在其他之上,依此类推,它也慢慢加载

我在做情节时所做的是这个:

    #C0 and C1
    plt.figure(figsize=(15,9))
    plt.xlabel('Day')
    plt.ylabel('Voltage')
    #3 plots at the same figure bacause of the three values from the read 
    plt.plot(C0Temp, C1Temp, label = "Voltage", color = LineColorTemp1Text)
    plt.plot(C2Temp, C3Temp, label="Max", color = 'r')
    plt.plot(C4Temp, C5Temp, label="Min", color = 'g')
    plt.legend()
    
    #This right here should detect days when ploting and 
    #probably read all month if possible
    locator = mdates.AutoDateLocator(minticks=12, maxticks=24)
    plt.gcf().axes[0].xaxis.set_major_locator(locator)
    plt.xticks(rotation = 45)

什么也没发生,任何帮助都会很棒! 预先感谢

python pandas dataframe matplotlib
1个回答
0
投票

您似乎正在尝试从

.txt
文件中绘制数据,其中每行代表时间戳、电压读数和相应的日期。要创建显示每日数据的绘图,

您可以按照以下步骤操作:

  1. 从文本文件中读取数据: 首先,因为您已经使用 Python 的内置文件处理或

    .txt
    库将数据读入 DataFrame,从而从
    pandas
    文件中读取数据。

  2. 解析时间戳和日期: 从每一行中提取时间戳和日期。您可以使用逗号和空格分隔行来分隔值。

  3. 按日期对数据进行分组: 按日期(天)对数据进行分组,以便您可以汇总每天的电压读数。

  4. 绘制数据: 最后,创建一个图,其中 x 轴代表日期,y 轴代表聚合电压读数。

如何使用

pandas
matplotlib
实现此目的:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Read data from your .txt file (replace 'your_file.txt' with the actual file path)
df = pd.read_csv("your_file.txt", header=None, names=["Timestamp", "C0", "C1", "C2", "Date"])

# Convert the Timestamp column to datetime format
df["Timestamp"] = pd.to_datetime(df["Timestamp"], format="%H:%M:%S")

# Group data by date and calculate the mean voltage for each day
daily_voltage = df.groupby("Date")["C0"].mean()

# Create the plot
plt.figure(figsize=(15, 9))
plt.xlabel("Day")
plt.ylabel("Voltage")
plt.plot(daily_voltage.index, daily_voltage.values, label="Voltage", color="blue")
plt.legend()

# Set x-axis ticks to show dates
locator = mdates.AutoDateLocator(minticks=12, maxticks=24)
plt.gcf().axes[0].xaxis.set_major_locator(locator)
plt.xticks(rotation=45)

plt.title("Daily Voltage Readings")
plt.show()

确保将

"your_file.txt"
替换为数据文件的实际路径。根据您的数据格式根据需要调整列名称(
"C0"
"C1"
等)。

此代码将创建一个图,其中每个点代表特定日期的平均电压读数。 x 轴将显示日期,y 轴将显示电压值。

© www.soinside.com 2019 - 2024. All rights reserved.