python - Matplotlib x 轴时间错误

标签 python matplotlib

我有一些由前工程师编写的 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()

enter image description here

您还可以使用 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()

enter image description here

关于python - Matplotlib x 轴时间错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47076428/

相关文章:

python - Pyparsing 左侧为Optional

php - 缩放数据库中的临时记录以计算总数以停止过度订阅

pandas - 数据帧的累积直方图

Python:如何绘制以颜色编码值作为背景的信号?

python - 是否可以在 matplotlib 中创建按钮,以便我可以像在 GUI 界面中那样做?

exec 中的 python 字典理解使用全局变量而不是局部变量

python - 如何使用 python 在 json 中动态修改我的 datetime 对象?

python - 在 Beautifulsoup 中提取值(value)

python - 如何绘制水平堆叠的热图或堆叠的网格?

python - 将 s 转换为 h :m in y-axis in matplotlib (data_plot)