一、数据介绍及预处理
本次可视化的数据集来源于空气质量监测平台,主要内容为北京市2014年1月1日至2020年12月30日AQI数据(空气质量指数),共2510条时序数据。
基本字段 | 含义 |
---|---|
Time | 日期 (2014/1/1—2020/12/29) |
AQI | 空气质量指数 |
根据AQI的值,可对其分为六种空气质量等级,代码处理如下:
import pandas as pd
data = pd.read_csv('beijing_aqi_daily.csv',encoding='gbk')
def rank_label(x):
if x<50:
return '优'
elif x>50 and x<100:
return '良'
elif x>100 and x<150:
return '轻度污染'
elif x>150 and x<200:
return '中度污染'
elif x>200 and x<300:
return '重度污染'
else:
return '严重污染'
data['rank_label'] = data['AQI'].apply(rank_label)
二、北京市空气质量等级分布
全部代码
import numpy as np
import os
import pandas as pd
os.chdir('C:/users/dell/Desktop/')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams['font.sans-serif'] = 'kaiti'
plt.rcParams['axes.unicode_minus'] = False
%config InlineBackend.figure_format='svg' #矢量化图片,更加清晰
data = pd.read_csv('beijing_aqi_daily.csv',encoding='gbk')
def rank_label(x):
if x<50:
return '优'
elif x>50 and x<100:
return '良'
elif x>100 and x<150:
return '轻度污染'
elif x>150 and x<200:
return '中度污染'
elif x>200 and x<300:
return '重度污染'
else:
return '严重污染'
def process_data(data):
data['year']=data['Time'].str.split('/').str[0]
data['month']=data['Time'].str.split('/').str[1]
data['rank_label'] = data['AQI'].apply(rank_label)
data[['year','month']] = data[['year','month']].astype('int')
return data
def plot_stack_bar(data,time,png_title):
columns = ['优','良','轻度污染','中度污染','重度污染','严重污染']
df = pd.crosstab(data[time],data['rank_label'],normalize='index')
df = df[columns]
index = df.index
plt.figure(figsize=(12,5))
color_list = [(67/256,206/256,23/256),(239/256,220/256,49/256),(255/256,170/256,0/256),
(255/256,64/256,26/256),(210/256,0/256,64/256),(156/256,10/256,78/256)]
plt.bar(index,df['优'],color=color_list[0])
for i in range(1,6):
plt.bar(index,df[columns[i]],
bottom = np.sum(df.iloc[:,0:i],axis=1),
color = color_list[i])
plt.xticks(index,df.index)
plt.title(png_title)
plt.ylabel('百分比')
plt.legend(columns,loc=2,framealpha=0.2,bbox_to_anchor=(1.0,1.0))
plt.show()
if __name__=='__main__':
data = process_data(data)
plot_stack_bar(data,'month','北京市月度空气等级分布')
1. 月度空气等级分布
2. 年度空气等级分布
以上就是本次分享的全部内容,数据链接如下:
链接:https://pan.baidu.com/s/11NxESPL3SVlzLVsHJKa5HA
提取码:pnm2