python 天气数据可视化的 天气预报_爬取天气信息并到简单数据可视化

该博客展示了如何使用Python的requests、pandas和matplotlib库爬取并可视化天气历史数据。通过访问天气历史网站获取昌平2019年11月的天气信息,解析HTML内容,存储到CSV文件中,然后进行数据清洗,提取最高和最低气温,最后利用matplotlib绘制气温变化图。
摘要由CSDN通过智能技术生成

import requests

import pandas as pd

from matplotlib import pyplot as plt

from lxml import etree

url = 'http://www.tianqihoubao.com/lishi/changping/month/201911.html'

headers = {

'user-agent': 'mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/78.0.3904.97 safari/537.36'

}

dates,conditions,tem = [],[],[]

response = requests.get(url,headers=headers).text

tree = etree.html(response)

tr_list = tree.xpath('//*[@id="content"]/table//tr')

for tr in tr_list[1:]:

date = tr.xpath('./td[1]/a/text()')[0].replace('\r\n','').strip()

condition = tr.xpath('./td[2]/text()')[0].replace('\r\n ','').strip()

temp = tr.xpath('./td[3]/text()')[0].replace('\r\n ','').strip()

dates.append(date)

conditions.append(condition)

tem.append(temp)

_date = pd.dataframe()

_date['日期'] = dates

_date['天气状况'] = conditions

_date['气温'] = tem

# 重写索引()

pd.concat([_date,]).reset_index(drop=true)

data = pd.concat([_date,])

data.to_csv('changping.csv',index=false,encoding='utf-8')

# 数据可视化

# 解决中文编码问题

plt.rcparams['font.sans-serif'] = ['simhei']

# 解决负号显示问题

plt.rcparams['axes.unicode_minus'] = false

df = pd.read_csv('guangzhou.csv')

# print((df.isnull()).sum())#检查是否有空值,并求出数量

# 日期 0

# 天气状况 0

# 气温 0

# dtype: int64

df['最高气温'] = df['气温'].str.split('/',expand=true)[0]

df['最低气温'] = df['气温'].str.split('/',expand=true)[1]

df['最高气温'] = df['最高气温'].map(lambda x:int(x.replace('℃','')))

df['最低气温'] = df['最低气温'].map(lambda x:int(x.replace('℃','')))

dates = df['日期']

tem_hight = df['最高气温']

tem_low = df['最低气温']

flg = plt.figure(dpi=128,figsize=(10,6)) #展示生成的图大大小

plt.plot(dates, tem_hight, c='red', alpha=0.5)#c='red',:颜色 alpha=0.5:透明底

plt.plot(dates, tem_low, c='blue', alpha=0.5)

plt.fill_between(dates,tem_hight,tem_low,facecolor='blue',alpha=0.2)

# 图标格式

plt.title('北京昌平2019年11月天气',fontsize=24) #标题

plt.xlabel('日期',fontsize=6) #横坐标标题以及字体大小

flg.autofmt_xdate()

plt.ylabel('气温',fontsize=12) #纵坐标标题以及字体大小

plt.tick_params(axis='both',which='major',labelsize=10)

plt.xticks(dates[::20])

plt.show()

9eaca268e920b97f57849edb2cc99051.png

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值