簡體   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