Skip to main content
 首页 » 编程设计

python之Matplotlib x 轴时间错误

2024年10月01日6zhujiabin

我有一些以前的工程师编写的 Python 代码,我正在尝试添加到其中。该脚本记录串行字符串输入的值,并根据时间将字符串中的值记录在 CSV 文件中。 CSV 文件如下所示

12h35m15s,0.01t 
12h35m16s,0.02t 
12h35m17s,0.05t 
12h35m18s,0.15t 
12h35m19s,0.21t 
12h35m20s,0.23t 
12h35m21s,0.20t 
12h35m22s,0.21t 
12h35m23s,0.22t 
12h35m24s,0.26t 

等等……

我所做的是在代码中添加一个部分,这样当您按下一个按钮时,它会使用 matplotlib 生成 CSV 文件中的数据图表。

我遇到的问题是 matplotlib 无法以 12h25m15s 格式绘制时间,因为它不是 float 。我更改了代码以从 CSV 文件中删除 h、m 和 s,但问题是秒值。 1 秒处的秒数是 1s,而不是 01s,因此我绘制的值将是例如:

12358  (at 12h25m8s) 
12359  (at 12h25m9s) 
123510 (at 12h25m10s) 
123511 (at 12h25m11s) 
123512 (at 12h25m12s) 
123513 (at 12h25m13s) 

然后到 12 点 36 分

12361  (at 12h36m1s) 
12362  (at 12h36m2s) 

等等……

这意味着当绘制我的图表时,它会将 12h36m1s 视为低于 12h35m10s 的值,并混淆数据在图表中的位置。

我需要找到两个解决方案之一:

1) 更正时间格式,使matplotlib正确绘制时间 2) 将我的 x 轴值设置为正在绘制的数据记录数。 IE。如果我有 50 个 y 数据记录,我的 x 轴就是 1-50 而不是时间。

有人可以帮忙吗?

我的图表代码是:

import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
import datetime as dt 
import numpy as np 
 
s = open('log0.csv','r').read() 
 
CSVunits = ('kN', 'T', 'lb', 'kg', 't')  
for c in CSVunits: 
    s = ''.join( s.split(c) ) 
 
out_file = open('graph.csv','w') 
out_file.write(s) 
out_file.close() 
 
data = [['13h10m5s'],['13h20m5s'],['13h30m5s'],['13h40m5s'],['13h50m5s'],['14h0m5s']] 
#data = np.loadtxt('graph.csv', delimiter=',', skiprows=4,usecols=[0]) 
x = [mdates.date2num(dt.datetime.strptime(x[0], '%Hh%Mm%Ss')) for x in data] 
y = np.loadtxt('graph.csv', delimiter=',', skiprows=4,usecols=[1]) 
 
fig,ax = plt.subplots(1) 
 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S')) 
ax.plot_date(x, y, '-') # '-' adds the line on the graph joining points 
 
plt.xlabel('Time') 
plt.ylabel('Load Value') 
plt.title('Graph Showing Load Against Time\n') 
 
plt.show() 

当我运行它时出现错误:

ValueError:float() 的无效文字:12h35m15s

为了清楚起见,在我的数据示例中,1、2 和 3 只是指示 CSV 文件中的行,没有包含 1、2 和 3 的列或数据。它只是时间和浮点值我的 CSV 文件中有。

谢谢

请您参考如下方法:

想象你的数据看起来像

1   12h35m8s    0.02 
2   12h35m9s    0.04 
3   12h35m10s   0.06 
4   12h35m11s   0.07 
5   12h35m12s   0.08 
6   12h35m13s   0.06 
7   12h35m15s   0.05 
8   12h35m16s   0.02 
9   12h35m17s   0.03 
10  12h36m1s    0.04 
11  12h36m2s    0.03 

您可以通过 pandas 读取并直接绘制它,

import pandas as pd 
import matplotlib.pyplot as plt 
 
df = pd.read_csv("data/timetable2.txt", delim_whitespace=True, header=None,  
                 names=["time","quantitiy"], index_col=0) 
df["time"] = pd.to_datetime(df["time"], format="%Hh%Mm%Ss") 
 
df.set_index("time").plot() 
 
plt.show() 

您还可以使用 matplotlib,其优势是可以更好地控制时间的表示方式(例如,您可以在轴上使用原始格式 "%Hh%Mm%Ss")。

import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates 
 
df = pd.read_csv("data/timetable2.txt", delim_whitespace=True, header=None,  
                 names=["time","quantity"], index_col=0) 
df["time"] = pd.to_datetime(df["time"], format="%Hh%Mm%Ss") 
 
plt.plot(df["time"],df["quantity"]) 
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Hh%Mm%Ss")) 
 
plt.show()