ToB企服应用市场:ToB评测及商务社交产业平台

标题: 近段时间天气暴热,所以采集北上广深去年天气数据,制作可视化图看下 [打印本页]

作者: 水军大提督    时间: 2022-8-20 21:36
标题: 近段时间天气暴热,所以采集北上广深去年天气数据,制作可视化图看下
前言

最近天气异常暴热,看到某些地方地表温度居然达到70°,这就离谱
所以就想采集一下天气的数据,做个可视化图,回忆一下去年的天气情况

开发环境

对于本篇文章有疑问的同学可以加【资料白嫖、解答交流群:753182387】

天气数据采集

1. 发送请求
  1. url = 'https://tianqi.2345.com/Pc/GetHistory?areaInfo%5BareaId%5D=54511&areaInfo%5BareaType%5D=2&date%5Byear%5D=2022&date%5Bmonth%5D=5'
  2. response = requests.get(url)
  3. print(response)
复制代码
 
返回: 请求成功

2. 获取数据
  1. print(response.json())
复制代码
 

3. 解析数据 天气信息提取出来

结构化数据解析:Python字典取值
非结构化数据解析:网页结构
  1. json_data = response.json()
  2. html_data = json_data['data']
  3. select = parsel.Selector(html_data)
  4. trs = select.css('table tr')
  5. for tr in trs[1:]:
  6.     # 网页结构
  7.     # html网页 <td>asdfwaefaewfweafwaef</td> <a></a>
  8.     # ::text: 我需要这个 标签里面的文本内容
  9.     td = tr.css('td::text').getall()
  10.     print(td)
复制代码
 
4. 保存数据
  1. with open('天气数据.csv', encoding='utf-8', mode='a', newline='') as f:
  2.     csv_writer = csv.writer(f)
  3.     csv_writer.writerow(td)
复制代码
 


数据可视化效果

读取数据
  1. data = pd.read_csv('天气数据.csv')
  2. data
复制代码
 

分割日期/星期
  1. data[['日期','星期']] = data['日期'].str.split(' ',expand=True,n=1)
  2. data
复制代码
 

去除多余字符
  1. data[['最高温度','最低温度']] = data[['最高温度','最低温度']].apply(lambda x: x.str.replace('°',''))
  2. data.head()
复制代码
 

北上广深2021年10月份天气热力图分布
  1. import matplotlib.pyplot as plt
  2. import matplotlib.colors as mcolors
  3. import seaborn as sns
  4. #设置全局默认字体 为 雅黑
  5. plt.rcParams['font.family'] = ['Microsoft YaHei']
  6. # 设置全局轴标签字典大小
  7. plt.rcParams["axes.labelsize"] = 14  
  8. # 设置背景
  9. sns.set_style("darkgrid",{"font.family":['Microsoft YaHei', 'SimHei']})  
  10. # 设置画布长宽 和 dpi
  11. plt.figure(figsize=(18,8),dpi=100)
  12. # 自定义色卡
  13. cmap = mcolors.LinearSegmentedColormap.from_list("n",['#95B359','#D3CF63','#E0991D','#D96161','#A257D0','#7B1216'])
  14. # 绘制热力图
  15. ax = sns.heatmap(data_pivot, cmap=cmap, vmax=30,
  16.                  annot=True, # 热力图上显示数值
  17.                  linewidths=0.5,
  18.                 )
  19. # 将x轴刻度放在最上面
  20. ax.xaxis.set_ticks_position('top')
  21. plt.title('北京最近10个月天气分布',fontsize=16) #图片标题文本和字体大小
  22. plt.show()
复制代码
 




北京2021年每日最高最低温度变化
  1. color0 = ['#FF76A2','#24ACE6']
  2. color_js0 = """new echarts.graphic.LinearGradient(0, 1, 0, 0,
  3.     [{offset: 0, color: '#FFC0CB'}, {offset: 1, color: '#ed1941'}], false)"""
  4. color_js1 = """new echarts.graphic.LinearGradient(0, 1, 0, 0,
  5.     [{offset: 0, color: '#FFFFFF'}, {offset: 1, color: '#009ad6'}], false)"""
  6. tl = Timeline()
  7. for i in range(0,len(data_bj)):
  8.     coordy_high = list(data_bj['最高温度'])[i]
  9.     coordx = list(data_bj['日期'])[i]
  10.     coordy_low = list(data_bj['最低温度'])[i]
  11.     x_max = list(data_bj['日期'])[i]+datetime.timedelta(days=10)
  12.     y_max = int(max(list(data_bj['最高温度'])[0:i+1]))+3
  13.     y_min = int(min(list(data_bj['最低温度'])[0:i+1]))-3
  14.     title_date = list(data_bj['日期'])[i].strftime('%Y-%m-%d')
  15.     c = (
  16.         Line(
  17.             init_opts=opts.InitOpts(
  18.             theme='dark',
  19.             #设置动画
  20.             animation_opts=opts.AnimationOpts(animation_delay_update=800),#(animation_delay=1000, animation_easing="elasticOut"),
  21.             #设置宽度、高度
  22.             width='1500px',
  23.             height='900px', )
  24.         )
  25.         .add_xaxis(list(data_bj['日期'])[0:i])
  26.         .add_yaxis(
  27.             series_name="",
  28.             y_axis=list(data_bj['最高温度'])[0:i], is_smooth=True,is_symbol_show=False,
  29.             linestyle_opts={
  30.                    'normal': {
  31.                        'width': 3,
  32.                        'shadowColor': 'rgba(0, 0, 0, 0.5)',
  33.                        'shadowBlur': 5,
  34.                        'shadowOffsetY': 10,
  35.                        'shadowOffsetX': 10,
  36.                        'curve': 0.5,
  37.                        'color': JsCode(color_js0)
  38.                    }
  39.                },
  40.             itemstyle_opts={
  41.             "normal": {
  42.                 "color": JsCode(
  43.                     """new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
  44.                 offset: 0,
  45.                 color: '#ed1941'
  46.             }, {
  47.                 offset: 1,
  48.                 color: '#009ad6'
  49.             }], false)"""
  50.                 ),
  51.                 "barBorderRadius": [45, 45, 45, 45],
  52.                 "shadowColor": "rgb(0, 160, 221)",
  53.             }
  54.         },
  55.         )
  56.         .add_yaxis(
  57.             series_name="",
  58.             y_axis=list(data_bj['最低温度'])[0:i], is_smooth=True,is_symbol_show=False,
  59. #             linestyle_opts=opts.LineStyleOpts(color=color0[1],width=3),
  60.             itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_js1)),
  61.             linestyle_opts={
  62.                    'normal': {
  63.                        'width': 3,
  64.                        'shadowColor': 'rgba(0, 0, 0, 0.5)',
  65.                        'shadowBlur': 5,
  66.                        'shadowOffsetY': 10,
  67.                        'shadowOffsetX': 10,
  68.                        'curve': 0.5,
  69.                        'color': JsCode(color_js1)
  70.                    }
  71.                },
  72.         )
  73.         .set_global_opts(
  74.             title_opts=opts.TitleOpts("北京2021年每日最高最低温度变化\n\n{}".format(title_date),pos_left=330,padding=[30,20]),
  75.             xaxis_opts=opts.AxisOpts(type_="time",max_=x_max),#, interval=10,min_=i-5,split_number=20,axistick_opts=opts.AxisTickOpts(length=2500),axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="grey"))
  76.             yaxis_opts=opts.AxisOpts(min_=y_min,max_=y_max),#坐标轴颜色,axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="grey"))
  77.         )
  78.     )
  79.     tl.add(c, "{}".format(list(data_bj['日期'])[i]))
  80.     tl.add_schema(
  81.         axis_type='time',
  82.         play_interval=100,  # 表示播放的速度
  83.         pos_bottom="-29px",
  84.         is_loop_play=False, # 是否循环播放
  85.         width="780px",
  86.         pos_left='30px',
  87.         is_auto_play=True,  # 是否自动播放。
  88.         is_timeline_show=False)
  89. tl.render_notebook()
复制代码
 

北上广深10月份每日最高气温变化
  1. # 背景色
  2. background_color_js = (
  3.     "new echarts.graphic.LinearGradient(0, 0, 0, 1, "
  4.     "[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
  5. )
  6. # 线条样式
  7. linestyle_dic = { 'normal': {
  8.                     'width': 4,  
  9.                     'shadowColor': '#696969',
  10.                     'shadowBlur': 10,  
  11.                     'shadowOffsetY': 10,  
  12.                     'shadowOffsetX': 10,  
  13.                     }
  14.                 }
  15.    
  16. timeline = Timeline(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js),
  17.                                             width='980px',height='600px'))
  18. bj, gz, sh, sz= [], [], [], []
  19. all_max = []
  20. x_data = data_10[data_10['城市'] == '北京']['日'].tolist()
  21. for d_time in range(len(x_data)):
  22.     bj.append(data_10[(data_10['日'] == x_data[d_time]) & (data_10['城市']=='北京')]["最高温度"].values.tolist()[0])
  23.     gz.append(data_10[(data_10['日'] == x_data[d_time]) & (data_10['城市']=='广州')]["最高温度"].values.tolist()[0])
  24.     sh.append(data_10[(data_10['日'] == x_data[d_time]) & (data_10['城市']=='上海')]["最高温度"].values.tolist()[0])
  25.     sz.append(data_10[(data_10['日'] == x_data[d_time]) & (data_10['城市']=='深圳')]["最高温度"].values.tolist()[0])
  26.    
  27.     line = (
  28.         Line(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js),
  29.                                      width='980px',height='600px'))
  30.         .add_xaxis(
  31.             x_data,
  32.                   )
  33.         
  34.         .add_yaxis(
  35.             '北京',
  36.             bj,
  37.             symbol_size=5,
  38.             is_smooth=True,
  39.             is_hover_animation=True,
  40.             label_opts=opts.LabelOpts(is_show=False),
  41.         )
  42.   
  43.         .add_yaxis(
  44.             '广州',
  45.             gz,
  46.             symbol_size=5,
  47.             is_smooth=True,
  48.             is_hover_animation=True,
  49.             label_opts=opts.LabelOpts(is_show=False),
  50.         )
  51.         .add_yaxis(
  52.             '上海',
  53.             sh,
  54.             symbol_size=5,
  55.             is_smooth=True,
  56.             is_hover_animation=True,
  57.             label_opts=opts.LabelOpts(is_show=False),
  58.             
  59.         )
  60.         .add_yaxis(
  61.             '深圳',
  62.             sz,
  63.             symbol_size=5,
  64.             is_smooth=True,
  65.             is_hover_animation=True,
  66.             label_opts=opts.LabelOpts(is_show=False),
  67.             
  68.         )
  69.         
  70.         .set_series_opts(linestyle_opts=linestyle_dic)
  71.         .set_global_opts(
  72.             title_opts=opts.TitleOpts(
  73.                 title='北上广深10月份最高气温变化趋势',
  74.                 pos_left='center',
  75.                 pos_top='2%',
  76.                 title_textstyle_opts=opts.TextStyleOpts(color='#DC143C', font_size=20)),
  77.             
  78.             tooltip_opts=opts.TooltipOpts(
  79.                 trigger="axis",
  80.                 axis_pointer_type="cross",
  81.                 background_color="rgba(245, 245, 245, 0.8)",
  82.                 border_width=1,
  83.                 border_color="#ccc",
  84.                 textstyle_opts=opts.TextStyleOpts(color="#000"),
  85.         ),
  86.             xaxis_opts=opts.AxisOpts(
  87. #                 axislabel_opts=opts.LabelOpts(font_size=14, color='red'),
  88. #                 axisline_opts=opts.AxisLineOpts(is_show=True,
  89. #                 linestyle_opts=opts.LineStyleOpts(width=2, color='#DB7093'))
  90.                 is_show = False
  91.             ),
  92.                
  93.             
  94.             yaxis_opts=opts.AxisOpts(
  95.                 name='最高气温',            
  96.                 is_scale=True,
  97. #                 min_= int(min([gz[d_time],sh[d_time],sz[d_time],bj[d_time]])) - 10,
  98.                 max_= int(max([gz[d_time],sh[d_time],sz[d_time],bj[d_time]])) + 10,
  99.                 name_textstyle_opts=opts.TextStyleOpts(font_size=16,font_weight='bold',color='#5470c6'),
  100.                 axislabel_opts=opts.LabelOpts(font_size=13,color='#5470c6'),
  101.                 splitline_opts=opts.SplitLineOpts(is_show=True,
  102.                                                   linestyle_opts=opts.LineStyleOpts(type_='dashed')),
  103.                 axisline_opts=opts.AxisLineOpts(is_show=True,
  104.                                         linestyle_opts=opts.LineStyleOpts(width=2, color='#5470c6'))
  105.             ),
  106.             legend_opts=opts.LegendOpts(is_show=True, pos_right='1%', pos_top='2%',
  107.                                         legend_icon='roundRect',orient = 'vertical'),
  108.         ))
  109.    
  110.     timeline.add(line, '{}'.format(x_data[d_time]))
  111. timeline.add_schema(
  112.     play_interval=1000,          # 轮播速度
  113.     is_timeline_show=True,      # 是否显示 timeline 组件
  114.     is_auto_play=True,          # 是否自动播放
  115.     pos_left="0",
  116.     pos_right="0"
  117. )
  118. timeline.render_notebook()
复制代码
 


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4