可视化实例(二)Python绘制堆积柱形图——以北京市空气质量为例

该博客介绍了基于2014年至2020年北京市的空气质量数据进行的可视化分析。通过读取CSV数据,将AQI转换为六个空气质量等级,并进行了月度和年度的等级分布展示。使用了Python的pandas和matplotlib库进行数据处理和图表绘制,以直观呈现不同等级的占比情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、数据介绍及预处理

本次可视化的数据集来源于空气质量监测平台,主要内容为北京市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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值