python爬取济南最近30日天气并绘制折线图

刚开始学plt,写一个相对完善的折线图用以加深记忆
1486077-20190508104844482-2004351273.png

import re

import requests
from matplotlib import pyplot as plt

headers = {
    'Host': 'www.yangshitianqi.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
}
# 获取济南近30天的最低温和最高温
html = requests.get('https://www.yangshitianqi.com/jinan/30tian.html',
                    headers=headers).text
# 使用正则提取数据
pattern_temperature = r'<div class="fl i3 nz">(\d+~\d+)℃</div>'
pattern_date = r'<div class="t2 nz">(\d\d\.\d\d)</div>'
temperature = re.findall(pattern_temperature, html)
date = re.findall(pattern_date, html)

# 整理数据
max_d = [int(i.split('~')[1]) for i in temperature]
print(max_d)
min_d = [int(i.split('~')[0]) for i in temperature]
print(min_d)
# 近30日最低温和最高温
max_m = max(max_d)
min_m = min(min_d)
# 近30日最低温最高温所处的日期(第几天)
max_m_d = max_d.index(max_m)
min_m_d = min_d.index(min_m)
# 日期
date = [i.split('.')[0] + '月' + i.split('.')[1] + '日' for i in date]

# 定义图像质量
plt.figure(figsize=(18.5, 9), dpi=180)

# 解决中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 绘制图像
plt.plot(range(30), max_d, linestyle=':')
plt.plot(range(30), min_d, linestyle=':')

# 显示日期
plt.xticks(range(30), date, rotation=315)

# xy轴标识
plt.xlabel('日期', size=18)
plt.ylabel('温度/℃', size=18)
plt.title('济南近30日天气情况', size=36)

# 标记最高温和最低温
plt.text(
    # x轴坐标
    max_m_d,
    # y轴坐标
    max_m + 1,
    # 文字
    f'最高温,{max_m}℃',
    # 字体大小
    fontsize=16,
    # 文字颜色
    color='red',
    # 相对位置-水平
    ha='center',
    # 相对位置-垂直
    va='center',
    # 透明度
    alpha=1
)
plt.text(
    # x轴坐标
    min_m_d,
    # y轴坐标
    min_m - 1,
    # 文字
    f'最低温,{min_m}℃',
    # 字体大小
    fontsize=16,
    # 文字颜色
    color='blue',
    # 相对位置-水平
    ha='center',
    # 相对位置-垂直
    va='center',
    # 透明度
    alpha=1
)

# 显示网格
plt.grid(axis='y', alpha=0.2)
# 保存图像
plt.savefig('a.png')
# 显示图像
plt.show()
posted on 2019-05-08 10:53 凉云 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liangyun/p/10830514.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值