繁体   English   中英

使用pandas在matplotlib中绘图

[英]Plotting in matplotlib using pandas

我试图用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轴绘制为定义的时间,但无济于事。

在此输入图像描述

将您的纪元时间戳转换为datetime并使用pandas内置轴标签格式。 尝试替换这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM