当前位置:   article > 正文

基于Python的北京天气数据可视化分析_python天气可视化每月气温折线图

python天气可视化每月气温折线图

项目用到库

  1. import numpy as np
  2. import pandas as pd
  3. import datetime
  4. from pyecharts.charts import Line
  5. from pyecharts.charts import Boxplot
  6. from pyecharts.charts import Pie,Grid
  7. from pyecharts import options as opts
  8. from pyecharts.charts import Calendar

1.2018 年北京AQI全年走势图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. attr = df['Date'].tolist() # 将 Date 转换为列表
  4. v1 = df['AQI'].tolist() # 将 AQI 转换为列表
  5. # 创建折线图
  6. line = (
  7. Line()
  8. .add_xaxis(attr)
  9. .add_yaxis("AQI值:", v1, is_smooth=True,
  10. areastyle_opts=opts.AreaStyleOpts(opacity=0.3, color="#000"),
  11. markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
  12. markpoint_opts=opts.MarkPointOpts(data=[
  13. opts.MarkPointItem(type_="max", name="最大值"),
  14. opts.MarkPointItem(type_="min", name="最小值")
  15. ]))
  16. .set_global_opts(title_opts=opts.TitleOpts(title="2018年北京AQI全年走势图",
  17. pos_top='5%',
  18. pos_left='center'),
  19. xaxis_opts=opts.AxisOpts(type_="category"),
  20. yaxis_opts=opts.AxisOpts(type_="value"))
  21. )
  22. # 将图表渲染到 HTML 文件
  23. line.render("./2018年北京AQI全年走势图.html")

结果如下: 

2.2018 年北京PM2.5全年走势图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. attr = df['Date'].tolist() # 将 Date 转换为列表
  4. v1 = df['PM'].tolist() # 将 PM 转换为列表
  5. # 创建折线图
  6. line = (
  7. Line()
  8. .add_xaxis(attr)
  9. .add_yaxis("PM2.5值:", v1, is_smooth=True,
  10. areastyle_opts=opts.AreaStyleOpts(opacity=0.3, color="#000"),
  11. markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
  12. markpoint_opts=opts.MarkPointOpts(data=[
  13. opts.MarkPointItem(type_="max", name="最大值"),
  14. opts.MarkPointItem(type_="min", name="最小值")
  15. ]))
  16. .set_global_opts(title_opts=opts.TitleOpts(title="2018年北京PM2.5全年走势图",
  17. pos_top='5%',
  18. pos_left='center'),
  19. xaxis_opts=opts.AxisOpts(type_="category"),
  20. yaxis_opts=opts.AxisOpts(type_="value"))
  21. )
  22. # 将图表渲染到 HTML 文件
  23. line.render("./2018年北京PM2.5全年走势图.html")

结果如下:

3.2018 年北京月均AQI走势图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # 提取 Date 和 AQI 的值
  4. dom = df[['Date', 'AQI']]
  5. # 提取月份
  6. df['month'] = df['Date'].apply(lambda x: x.split('/')[1])
  7. # 根据月份分组并计算每月的 AQI 平均值
  8. month_com = df.groupby('month')['AQI'].mean().reset_index()
  9. # 排序月份
  10. month_com = month_com.sort_values(by='month')
  11. # 构造月份标签
  12. attr = ["{}月".format(i) for i in range(1, 13)]
  13. # 获取每月的 AQI 平均值
  14. v1 = month_com['AQI'].tolist()
  15. v1 = ["{}".format(int(i)) for i in v1]
  16. # 创建折线图
  17. line = (
  18. Line()
  19. .add_xaxis(attr)
  20. .add_yaxis("AQI月均值", v1,
  21. markpoint_opts=opts.MarkPointOpts(data=[
  22. opts.MarkPointItem(type_="max", name="最大值"),
  23. opts.MarkPointItem(type_="min", name="最小值")
  24. ]))
  25. .set_global_opts(title_opts=opts.TitleOpts(title="2018年北京月均AQI走势图",
  26. pos_top='5%',
  27. pos_left='center'),
  28. xaxis_opts=opts.AxisOpts(type_="category"),
  29. yaxis_opts=opts.AxisOpts(type_="value"))
  30. )
  31. # 渲染图表到 HTML 文件
  32. line.render("./2018年北京月均AQI走势图.html")

结果如下:

4.2018 年北京月均PM2.5走势图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # 提取 Date 和 PM 的值
  4. dom = df[['Date', 'PM']]
  5. # 提取月份
  6. df['month'] = df['Date'].apply(lambda x: x.split('/')[1])
  7. # 根据月份分组并计算每月的 PM 平均值
  8. month_com = df.groupby('month')['PM'].mean().reset_index()
  9. # 排序月份
  10. month_com = month_com.sort_values(by='month')
  11. # 构造月份标签
  12. attr = ["{}月".format(i) for i in range(1, 13)]
  13. # 获取每月的 PM 平均值
  14. v1 = month_com['PM'].tolist()
  15. v1 = ["{}".format(int(i)) for i in v1]
  16. # 创建折线图
  17. line = (
  18. Line()
  19. .add_xaxis(attr)
  20. .add_yaxis("PM2.5月均值", v1,
  21. markpoint_opts=opts.MarkPointOpts(data=[
  22. opts.MarkPointItem(type_="max", name="最大值"),
  23. opts.MarkPointItem(type_="min", name="最小值")
  24. ]))
  25. .set_global_opts(title_opts=opts.TitleOpts(title="2018年北京月均PM2.5走势图",
  26. pos_top='5%',
  27. pos_left='center'),
  28. xaxis_opts=opts.AxisOpts(type_="category"),
  29. yaxis_opts=opts.AxisOpts(type_="value"))
  30. )
  31. # 渲染图表到 HTML 文件
  32. line.render("./2018年北京月均PM2.5走势图.html")

结果如下:

5.2018年北京季度AQI箱形图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # 提取 Date 和 AQI 的值
  4. dom = df[['Date', 'AQI']]
  5. data = [[], [], [], []]
  6. dom1, dom2, dom3, dom4 = data
  7. # 根据季度提取 AQI 值
  8. for date, aqi in zip(dom['Date'], dom['AQI']):
  9. month = int(date.split('/')[1])
  10. if month in [1, 2, 3]:
  11. dom1.append(aqi)
  12. elif month in [4, 5, 6]:
  13. dom2.append(aqi)
  14. elif month in [7, 8, 9]:
  15. dom3.append(aqi)
  16. else:
  17. dom4.append(aqi)
  18. # 创建箱形图
  19. boxplot = Boxplot()
  20. # 设置 x 轴和 y 轴数据
  21. x_axis = ['第一季度', '第二季度', '第三季度', '第四季度']
  22. y_axis = [dom1, dom2, dom3, dom4]
  23. y_axis = boxplot.prepare_data(y_axis)
  24. # 添加数据到箱形图
  25. boxplot.add_xaxis(x_axis)
  26. boxplot.add_yaxis("AQI", y_axis)
  27. # 设置图表全局选项
  28. boxplot.set_global_opts(title_opts=opts.TitleOpts(title="2018年北京季度AQI箱形图", pos_left='center', pos_top='6%'))
  29. # 渲染图表到 HTML 文件
  30. boxplot.render("./2018年北京季度AQI箱形图.html")

结果如下:

6.2018年北京季度PM2.5箱形图

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # 提取 Date 和 PM 的值
  4. dom = df[['Date', 'PM']]
  5. data = [[], [], [], []]
  6. dom1, dom2, dom3, dom4 = data
  7. # 根据季度提取 PM 值
  8. for date, pm in zip(dom['Date'], dom['PM']):
  9. month = int(date.split('/')[1])
  10. if month in [1, 2, 3]:
  11. dom1.append(pm)
  12. elif month in [4, 5, 6]:
  13. dom2.append(pm)
  14. elif month in [7, 8, 9]:
  15. dom3.append(pm)
  16. else:
  17. dom4.append(pm)
  18. # 创建箱形图
  19. boxplot = Boxplot()
  20. # 设置 x 轴和 y 轴数据
  21. x_axis = ['第一季度', '第二季度', '第三季度', '第四季度']
  22. y_axis = [dom1, dom2, dom3, dom4]
  23. y_axis = boxplot.prepare_data(y_axis)
  24. # 添加数据到箱形图
  25. boxplot.add_xaxis(x_axis)
  26. boxplot.add_yaxis("PM2.5", y_axis)
  27. # 设置图表全局选项
  28. boxplot.set_global_opts(title_opts=opts.TitleOpts(title="2018年北京季度PM2.5箱形图", pos_left='center', pos_top='6%'))
  29. # 渲染图表到 HTML 文件
  30. boxplot.render("./2018年北京季度PM2.5箱形图.html")

结果如下:

7.2018年北京全年空气质量情况

代码如下:

  1. # 读取数据
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # 根据 Quality_grade 分组
  4. rank_message = df.groupby(['Quality_grade'])
  5. # 计算每个 Quality_grade 的频数
  6. rank_com = rank_message['Quality_grade'].agg(['count'])
  7. rank_com.reset_index(inplace=True) # 重置索引
  8. rank_com_last = rank_com.sort_values('count', ascending=False) # 从大到小排序
  9. # 提取 Quality_grade 和对应的频数
  10. attr = rank_com_last['Quality_grade'].tolist()
  11. v1 = rank_com_last['count'].tolist()
  12. # 创建饼图
  13. pie = (
  14. Pie()
  15. .add("", [list(z) for z in zip(attr, v1)], radius=["40%", "75%"],
  16. label_opts=opts.LabelOpts(is_show=True, formatter="{b}: {d}%"))
  17. .set_global_opts(title_opts=opts.TitleOpts(title="2018年北京全年空气质量情况", pos_left='center', pos_top='0'),
  18. legend_opts=opts.LegendOpts(is_show=True, orient="vertical", pos_left="left", pos_top="10%"))
  19. )
  20. # 渲染图表到 HTML 文件
  21. pie.render('./2018年北京全年空气质量情况.html')

结果如下:

8.2018年北京PM2.5指数日历图

代码如下:

  1. # Read data from 'beijing_AQI_2018.csv'
  2. df = pd.read_csv('beijing_AQI_2018.csv')
  3. # Extract 'Date' and 'PM' columns
  4. dom = df[['Date', 'PM']]
  5. list1 = []
  6. # Compress the date and PM values into a list of lists
  7. for i, j in zip(dom['Date'], dom['PM']):
  8. time_list = i.split('/')
  9. time = datetime.date(int(time_list[0]), int(time_list[1]), int(time_list[2]))
  10. PM = int(j)
  11. list1.append([str(time), PM])
  12. # Create a calendar chart
  13. calendar = (
  14. Calendar(init_opts=opts.InitOpts(width="800px", height="400px"))
  15. .add(
  16. series_name="2018年北京PM2.5指数日历图",
  17. yaxis_data=list1,
  18. calendar_opts=opts.CalendarOpts(range_="2018"),
  19. )
  20. .set_global_opts(
  21. title_opts=opts.TitleOpts(title="2018年北京PM2.5指数日历图", pos_left="center",pos_top='50%'),
  22. visualmap_opts=opts.VisualMapOpts(
  23. max_=300, min_=0, orient="horizontal", is_piecewise=True,
  24. pos_top='60%', # 将视觉映射放置在图表的顶部
  25. pos_left='center' # 将视觉映射放置在图表的水平居中位置
  26. ),
  27. )
  28. )
  29. # Render the chart to an HTML file
  30. calendar.render('./2018年北京PM2.5指数日历图.html')

结果如下:

9.2018 年北上广深AQI全年走势图

代码如下:

  1. citys = ['beijing', 'shanghai', 'guangzhou', 'shenzhen']
  2. cityes_AQI = []
  3. # 遍历四个城市的数据
  4. for city in citys:
  5. filename = city + '_AQI' + '_2018.csv'
  6. aqi_data = pd.read_csv(filename)
  7. # 提取日期和AQI指数两列内容
  8. get_data = aqi_data[['Date', 'AQI']]
  9. # 获取每行数据的月份
  10. month_for_data = [j.split('/')[1] for j in get_data['Date']]
  11. aqi_data['Month'] = month_for_data
  12. # 求每个月AQI平均值
  13. month_AQI = aqi_data.groupby(['Month'])['AQI'].mean().reset_index()
  14. # 获取每个城市月均AQI的数据,转化为int数据类型
  15. city_AQI_data_int = month_AQI['AQI'].astype(int).tolist()
  16. cityes_AQI.append(city_AQI_data_int)
  17. months = [str(i) + '月' for i in range(1, 13)]
  18. line = (
  19. Line(init_opts=opts.InitOpts(width="800px", height="400px"))
  20. .add_xaxis(months)
  21. .add_yaxis("北京", cityes_AQI[0], color='red', label_opts=opts.LabelOpts(is_show=False))
  22. .add_yaxis("上海", cityes_AQI[1], color='purple', label_opts=opts.LabelOpts(is_show=False))
  23. .add_yaxis("广州", cityes_AQI[2], color='blue', label_opts=opts.LabelOpts(is_show=False))
  24. .add_yaxis("深圳", cityes_AQI[3], color='orange', label_opts=opts.LabelOpts(is_show=False))
  25. .set_global_opts(
  26. title_opts=opts.TitleOpts(title="2018年北上广深AQI全年走势图", pos_left='center', pos_top='0'),
  27. legend_opts=opts.LegendOpts(orient="horizontal", pos_top="8%"),
  28. )
  29. )
  30. line.render('./2018年北上广深AQI全年走势图.html') # 生成HTML文件,保存在当前目录下

结果如下:

10.2018 年北上广深PM2.5全年走势图

代码如下:

  1. import numpy as np
  2. import pandas as pd
  3. from pyecharts.charts import Line
  4. from pyecharts import options as opts
  5. citys = ['beijing', 'shanghai', 'guangzhou', 'shenzhen']
  6. cityes_AQI = []
  7. # 遍历四个城市的数据
  8. for city in citys:
  9. filename = city + '_AQI' + '_2018.csv'
  10. aqi_data = pd.read_csv(filename)
  11. # 提取日期和PM2.5指数两列内容
  12. get_data = aqi_data[['Date', 'PM']]
  13. # 获取每行数据的月份
  14. month_for_data = [j.split('/')[1] for j in get_data['Date']]
  15. aqi_data['Month'] = month_for_data
  16. # 求每个月PM2.5平均值
  17. month_AQI = aqi_data.groupby(['Month'])['PM'].mean().reset_index()
  18. # 获取每个城市月均PM2.5的数据,转化为int数据类型
  19. city_AQI_data_int = month_AQI['PM'].astype(int).tolist()
  20. cityes_AQI.append(city_AQI_data_int)
  21. months = [str(i) + '月' for i in range(1, 13)]
  22. line = (
  23. Line(init_opts=opts.InitOpts(width="800px", height="400px"))
  24. .add_xaxis(months)
  25. .add_yaxis("北京", cityes_AQI[0], color='red', label_opts=opts.LabelOpts(is_show=False))
  26. .add_yaxis("上海", cityes_AQI[1], color='purple', label_opts=opts.LabelOpts(is_show=False))
  27. .add_yaxis("广州", cityes_AQI[2], color='blue', label_opts=opts.LabelOpts(is_show=False))
  28. .add_yaxis("深圳", cityes_AQI[3], color='orange', label_opts=opts.LabelOpts(is_show=False))
  29. .set_global_opts(
  30. title_opts=opts.TitleOpts(title="2018年北上广深PM2.5全年走势图", pos_left='center', pos_top='0'),
  31. legend_opts=opts.LegendOpts(orient="horizontal", pos_top="8%"),
  32. )
  33. )
  34. line.render('./2018年北上广深PM2.5全年走势图.html') # 生成HTML文件,保存在当前目录下

结果如下:

11.2018 年北上广深全年空气质量情况

代码如下:

  1. citys = ['beijing', 'shanghai', 'guangzhou', 'shenzhen']
  2. v = []
  3. attrs = []
  4. for i in range(4):
  5. filename = citys[i] + '_AQI' + '_2018.csv'
  6. df = pd.read_csv(filename)
  7. # 根据 Quality_grade 分组
  8. Quality_grade_message = df.groupby(['Quality_grade'])
  9. # 每组的频数
  10. Quality_grade_com = Quality_grade_message['Quality_grade'].agg(['count'])
  11. Quality_grade_com.reset_index(inplace=True)
  12. Quality_grade_com_last = Quality_grade_com.sort_values('count', ascending=False)
  13. # 取 Quality_grade 的值
  14. Quality_grade_array = Quality_grade_com_last['Quality_grade'].values.tolist()
  15. attrs.append(Quality_grade_array)
  16. Quality_grade_count = Quality_grade_com_last['count'].values.tolist()
  17. v.append(Quality_grade_count)
  18. # 创建饼图并设置属性
  19. pie1 = (
  20. Pie()
  21. .add("北京", [list(z) for z in zip(attrs[0], v[0])], radius=["20%", "40%"], center=["30%", "27%"],)
  22. .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
  23. .set_global_opts(title_opts=opts.TitleOpts(title="北京", pos_left='27%', pos_top='25%'),
  24. legend_opts=opts.LegendOpts(orient="vertical", pos_right="5%", pos_top="35%"))
  25. )
  26. pie2 = (
  27. Pie()
  28. .add("上海", [list(z) for z in zip(attrs[1], v[1])], radius=["20%", "40%"], center=["70%", "27%"],)
  29. .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
  30. .set_global_opts(title_opts=opts.TitleOpts(title="上海", pos_left='67%', pos_top='25%'),
  31. legend_opts=opts.LegendOpts(is_show=False))
  32. )
  33. pie3 = (
  34. Pie()
  35. .add("广州", [list(z) for z in zip(attrs[2], v[2])], radius=["20%", "40%"], center=["30%", "77%"],)
  36. .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
  37. .set_global_opts(title_opts=opts.TitleOpts(title="广州", pos_left='27%', pos_top='75%'),
  38. legend_opts=opts.LegendOpts(is_show=False))
  39. )
  40. pie4 = (
  41. Pie()
  42. .add("深圳", [list(z) for z in zip(attrs[3], v[3])], radius=["20%", "40%"], center=["70%", "77%"],)
  43. .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
  44. .set_global_opts(title_opts=opts.TitleOpts(title="深圳", pos_left='67%', pos_top='75%'),
  45. legend_opts=opts.LegendOpts(is_show=False))
  46. )
  47. # 创建 Grid 并添加饼图
  48. grid = (
  49. Grid()
  50. .add(pie1, grid_opts=opts.GridOpts(pos_left="5%", pos_right="50%", pos_top="10%"))
  51. .add(pie2, grid_opts=opts.GridOpts(pos_left="55%", pos_right="5%", pos_top="10%"))
  52. .add(pie3, grid_opts=opts.GridOpts(pos_left="5%", pos_right="50%", pos_top="50%"))
  53. .add(pie4, grid_opts=opts.GridOpts(pos_left="55%", pos_right="5%", pos_top="50%"))
  54. )
  55. grid.render('./2018年北上广深全年空气质量情况.html')

结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/709847
推荐阅读
相关标签
  

闽ICP备14008679号