Python繪制溫度變化曲線


導入必要的第三方庫

from requests import get
import matplotlib.pyplot as plt
/usr/lib/python3/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/usr/lib/python3/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
from dateutil import parser
url = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallmeasurements/505307'
weather = get(url).json()
weather['items'][0]['ambient_temp']
9.77
weather['items'][0]
{'air_pressure': 982.51,
 'air_quality': 75.82,
 'ambient_temp': 9.77,
 'created_by': 'Test Brompton Academy',
 'created_on': '2016-11-19T22:50:00Z',
 'ground_temp': -1000,
 'humidity': 71.11,
 'id': 1707846,
 'rainfall': 0,
 'reading_timestamp': '2016-11-19T22:50:00Z',
 'updated_by': 'Test Brompton Academy',
 'updated_on': '2016-11-20T00:56:09.435Z',
 'weather_stn_id': 505307,
 'wind_direction': 111.92,
 'wind_gust_speed': 22.8,
 'wind_speed': 12.34}

迭代天氣數據集,取出溫度數據,並且保存到列表

利用for循環獲取溫度列表

temperatures = []
for record in weather['items']:
    temperature = record['ambient_temp']
    temperatures.append(temperature)

利用列表生成式來獲取溫度數據

temperatures = [record['ambient_temp'] for record in weather['items']]

把RaspberryPi的數據庫所用的日期轉換成Python中的datetime對象格式

parser.parse(weather['items'][0]['reading_timestamp'])
datetime.datetime(2016, 11, 19, 22, 50, tzinfo=tzutc())

用列表生成式來獲取日期列表

timestamps = [parser.parse(record['reading_timestamp']) for record in weather['items']]

繪制圖像

  1. 繪圖需要的代碼很少,首先聲明繪圖要用的數據集合,然后第二個用來展示數據:
## 繪制溫度時間變化圖
plt.plot(timestamps, temperatures)
plt.ylabel('溫度')
plt.xlabel('時間')
plt.show()

到此為止教程結束

拓展思考

  1. 比如物理的加速度實驗,用紙袋獲取數據后可以用這種方法繪圖
  2. 生物實驗觀測的數據繪圖
  3. 數學圖像,統計觀察

如果是實際實驗獲得的數據,獲取數據的過程可以大大簡化,這樣只需要8行左右的代碼就可以繪制一些實驗曲線



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM