思路
for循环每一年的数据,基于每一年的数据,创建每一年的Bar对象,并且将该对象添加到时间线timeline
中,最后设置自动播放并绘图
实现代码
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType# 注意编码格式必须是GB2312,否则中文乱码
f = open("./1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()f.close()# 第一行是无用数据
data_lines.pop(0)# 将数据转换为字典存储,即如下格式:
# {年份:[[国家, gdp], [国家, gdp], [国家, gdp]...] ,年份:[[国家, gdp], [国家, gdp], [国家, gdp]...] ,...}
data_dict = {}
for line in data_lines:line.strip()year = int(line.split(",")[0])country = line.split(",")[1]gdp = float(line.split(",")[2]) # 必须转为float,因为float可把科学计数法识别出来# 用异常判断字典里是否有指定的keytry:data_dict[year].append([country, gdp])except KeyError:data_dict[year] = [] # 构建新的字典元素data_dict[year].append([country, gdp]) # 每一年是一个字典对timeline = Timeline({"theme": ThemeType.LIGHT})# 排序年份
sorted_year_list = sorted(data_dict.keys())
for year in sorted_year_list:# 每一年按gdp降序排列获得前8个gdp最大的国家数据data_dict[year].sort(key=lambda element:element[1], reverse=True)year_data = data_dict[year][0:8] # 前8个listprint(year_data)x_data = []y_data = []for country_gdp in year_data:x_data.append(country_gdp[0])y_data.append(country_gdp[1] / 100000000) # y轴用gdp# 构建柱状图# 每一年的数据算时间线上的一个节点bar = Bar()# 让gdp最高的数据在最上面x_data.reverse()y_data.reverse()bar.add_xaxis(x_data)# 柱状图y轴数据显示在柱的右侧bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))# 反转x轴和y轴bar.reversal_axis()#bar.set_global_opts(title_opts=TitleOpts(title=f"{year}年全球前8GDP数据"))timeline.add(bar, str(year))timeline.add_schema(play_interval=1000, # 播放间隔时间 msis_timeline_show=True,is_auto_play=True,is_loop_play=False
)# 绘图
timeline.render("1960-2019全球gdp前8的国家.html")