使用pandas在matplotlib中打印

2024-10-02 14:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用2个y轴和一个共享的x轴来绘图。我已经到了这一点,但这不是我想要的x轴。你知道吗

这是我的密码:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("Live_data_test.xlsx","Sheet1")



timedat = df.loc[:, 'Time']
temperaturedat = df.loc[:, 'Temperature']
humiditydat = df.loc[:, 'Humidity']

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(timedat, temperaturedat, 'g-')
ax2.plot(timedat, humiditydat, 'b-')

ax1.set_xlabel('Time')
ax1.set_ylabel('Temperature', color='g')
ax2.set_ylabel('Humidity', color='b')

plt.show()

x轴标绘为0,1,2,。。。不管我有多少观点。它不是绘制定义的x轴,它应该是我在电子表格中设置的unix时间。你知道吗

电子表格:

Time    Temperature Humidity
1513753200  54  45
1513753201  55  48
1513753202  55  50
1513753203  56  52
1513753204  56  54
1513753205  57  54
1513753206  56  54
1513753207  56  55
1513753208  56  56
1513753209  55  56
1513753210  54  52
1513753211  53  50
1513753212  52  45
1513753213  51  45

当我打印(timedat)时,我得到:

0     1.513753e+09
1     1.513753e+09
2     1.513753e+09
3     1.513753e+09
4     1.513753e+09
5     1.513753e+09
6     1.513753e+09
7     1.513753e+09
8     1.513753e+09
9     1.513753e+09
10    1.513753e+09
11    1.513753e+09
12    1.513753e+09
13    1.513753e+09
Name: Time, dtype: float64

我相信将unix时间转换为H:M:sm/D/Y时间应该足够简单。我已经找了好几个小时,试图把x轴标为定义的时间,但没有结果。你知道吗

enter image description here


Tags: importdftimeas时间pltlocpd
2条回答

将历元时间戳转换为日期时间,并使用内置的轴标签格式。尝试替换此:

timedat = df.loc[:, 'Time']

有了这个:

timedat = pd.to_datetime(df['Time'], unit='s')

要将Time列从unix格式转换为字符串日期时间,请使用pd.to_datetime+dt.strftime-

df.Time = pd.to_datetime(df.Time, unit='s').dt.strftime('%H:%I:%S %m/%d/%y')
df

                 Time  Temperature  Humidity
0   07:07:00 12/20/17           54        45
1   07:07:01 12/20/17           55        48
2   07:07:02 12/20/17           55        50
3   07:07:03 12/20/17           56        52
4   07:07:04 12/20/17           56        54
5   07:07:05 12/20/17           57        54
6   07:07:06 12/20/17           56        54
7   07:07:07 12/20/17           56        55
8   07:07:08 12/20/17           56        56
9   07:07:09 12/20/17           55        56
10  07:07:10 12/20/17           54        52
11  07:07:11 12/20/17           53        50
12  07:07:12 12/20/17           52        45
13  07:07:13 12/20/17           51        45

相关问题 更多 >