需求:利用pyecharts模块实现柱状图动态展示1960-2019全球GDP前10国家变化
效果展示:
对于数据可视化,可基本分为两大步骤——数据预处理和绘图。
在开头导入所需模块pyecharts以及柱状图对应的包
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
一、数据预处理
#数据预处理
#读取数据
f = open("D:/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_list = f.readlines() #使用readlines可直接得到列表
f.close()
data_list.pop(0) #删除第一行无用数据
#将数据转换为字典,格式为
# {1960:[ [美国:gdp], [中国, gdp]......], 1961:[ [美国:gdp], [中国, gdp]......], ...... }
data_dict = dict() #定义空字典用于存放
for line in data_list:
year = int(line.split(",")[0])
country = line.split(",")[1]
gdp = float(line.split(",")[2]) #数据中包含使用科学计数法表示的数据,故强制转换float
try: #第一次循环时字典为空,并没有”1960“这个key,无法添加对应value
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = [] #将year的位置定义为空,相当于先占位
data_dict[year].append([country, gdp])
二、绘图
动态柱状图可以视为在时间线上有若干个时间点,每个时间点都有对应的柱状图,当这若干个柱状图随着时间点显示时,就能形成动态效果。
对于本练习来说,时间线就是1960年-2019年,每一年为一个时间点,每一年都有一张GDP图。
1、构建时间线对象,并选择LIGHT主题
#构建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
2、构建柱状图对象
(1)处理数据,得到x轴——“国家”,y轴——“GDP数值”(以亿为单位)
#排序年份
sorted_year_list = sorted(data_dict.keys()) #字典为无序的数据容器,在处理前需要排序
#排序gdp
for year in sorted_year_list:
data_dict[year].sort(key=lambda element:element[1], reverse=True)
#取出本年份排序前10的国家
year_data = data_dict[year][0:10]
#组装x轴和y轴数据
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0]) #x轴添加国家
y_data.append(country_gdp[1] / 100000000) #y轴添加gdp
(2)构建柱状图对象
#构建柱状图对象
bar = Bar()
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))
bar.reversal_axis()
#设置每一年柱状图的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球前10GDP")
)
timeline.add(bar, str(year)) #将柱状图加入时间线
(3)设置图像打开后自动播放,最后生成图像
#时间轴自动播放设置
timeline.add_schema(
is_timeline_show=True,
play_interval=1000, #播放间隔1000ms
is_auto_play=True,
is_loop_play=False
)
#生成图像
timeline.render("1960-2019全球GDP动态展示.html")
三、得到的图像文件,使用浏览器打开即可