Python/Arduino学習記録,備忘録

コツコツ学んだ学習記録と備忘録。現在Python,Arduino勉強中。

【Python#10】室内の温湿度データ読み込み&時系列グラフ作成

前回は以下の記事で,室内の温湿度をDHT11というセンサを用いて計測し,ArduinoとPC間のシリアル通信を用いてデータを飛ばし,Pythoncsvファイルに保存させることを達成した。
opuktr.hatenablog.com



今回はその保存したcsvファイルからデータを読み込み,グラフで表示させることを試みる。
表示の仕様としては,以下を考える。

  • csvファイルから温湿度データ読み込み
  • 温湿度データを時系列データとしてグラフ表示


[目次]

1. 必要素子(今回はなし)

今回はArduinoを使用していない為,無しとする。

2. 配線図(今回はなし)

今回はArduinoを使用していない為,無しとする。


3. Pythonコード

Python

# -*- coding: utf-8 -*-
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#変数の初期化
temp = []
humid = []
time = []
hi = []
length = [0]
l=0

#基準となる日時の指定
standard = datetime.datetime(2018,8,18,23,0,0) #2018/8/18 23:00:00を基準

for i in range(24):  #24時間分のデータ読み込み
    #ファイル名の指定
    filename = "temphumid_" + standard.strftime("%Y%m%d") + "_" + standard.strftime("%H") + ".csv"
    
    #datafram型として読み込み
    lstpd = pd.read_csv(filename,engine='python')
    
    #1つの変数に格納
    temp.append(lstpd["temp[℃]"])
    humid.append(lstpd["humid[%]"])
    hi.append(lstpd["heat index"])
    
    #x軸のラベル取得
    l = l + len(lstpd)
    length.append(l)
    time.append(standard.strftime("%H:%M"))
    
    #次の1時間に日時を変更
    standard = standard + datetime.timedelta(hours=1)

time.append(standard.strftime("%H:%M"))  #x軸のラベル取得

#データを時系列に連結&リスト化&Numpy配列に変換
temp = np.array(pd.concat(temp).values.tolist())
humid = np.array(pd.concat(humid).values.tolist())
hi = np.array(pd.concat(hi).values.tolist())

#グラフの作成
fig, ax1 = plt.subplots()

#温度
ax1.plot(temp,'C0',label="temp[℃]")

#湿度/不快指数
ax2 = ax1.twinx()  # 2軸目の設定
ax2.plot(humid,'C1',label="humid[%]")
ax2.plot(hi,'C2',label="heat index")

#凡例の設定
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, bbox_to_anchor=(0, 1.02, 1, .102),
           ncol=3,mode="expand", borderaxespad=0)

#y軸ラベルの設定
ax1.set_xlabel("time")
ax1.set_ylabel("temp[℃]")
ax1.grid(True) #補助線
ax2.set_ylabel("humid[%], heat index")

#x軸ラベルの設定
ax1.set_xticks(length)
ax1.set_xticklabels(time, rotation=90, fontsize='small')

#表示
plt.show()

4. 実行結果

f:id:opuktr:20180820225732p:plain

上図に室内の温湿度・不快指数を可視化した。

この図から

  • 夜と昼の温度差は約5℃
  • 8~9時頃から温度上昇が始まる
  • 室温が上がると湿度が下がる
  • 10~11時頃のピークはDHT11に直射日光が...笑
  • 18~22時頃まで温度が下がる

ということが読み取れる。

温度の分析を行うにあたっては,分解能が1℃単位というのは非常に粗い精度なので,もう少し細かい単位で扱えるようになるのが望ましい。

今1か所だけで,かつ有線で計測を行っている状態なので,これを複数個所かつ無線でデータを集めれるようなシステムを構築したい。ここからが,大変そうだ。