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行左右的代码就可以绘制一些实验曲线


原文地址:https://www.cnblogs.com/asworm/p/6358271.html