偶然看到网上国家统计数据,利用Python数据分析自己做了几种图表练习。主要采用Pandas来做数据统计,matplotlib来做图表可视化。
下面图表数据来源于网络。
饼状图
代码如下:
代码语言:python代码运行次数:0复制import matplotlib.pyplot as plt
import pandas as pd
import itertools
plt.rcParams['font.family']='sans-serif'
plt.rcParams['font.sans-serif']='SimHei'
df=pd.read_excel('d:/2018-2019年空气质量均值.xlsx')
df2=pd.read_excel('d:/2018-2019年空气质量均值.xlsx',1)
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
colNames=["二氧化硫","氮氧化物","烟尘","排放总量"]
years=["2018","2019"]
regionTypes=["省辖市","市辖区"]
def getPlot(colName,year,regionType):
df22=df2
if regionType=="市辖区":
df22=df2[df2['城市名']!='济源市']
g=df22.groupby(df22['城市名']).sum()
colStr='%s年%s_%s'%(year,colName,regionType)
explode = g[colStr].map(lambda x:0.1) # only "explode" the 2nd slice (i.e. 'Hogs')
sizes=g[colStr].apply(round)
labels=g.index
labels=sizes.reset_index().to_dict('records')
labels=map(lambda x:'%s(%dt)'%(x['城市名'],x[colStr]),labels)
labels=list(labels)
fig1, ax1 = plt.subplots(figsize=(8,8))
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
title="%s年各地市%s排放量分布(%s)"%(year,colName,regionType)
plt.title(title)
plt.savefig(title '.png')
for colName,year,regionType in itertools.product(colNames,years,regionTypes):
print(colName,year,regionType)
getPlot(colName,year,regionType)