以下是源代码:
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 构建时间限定对象
timeline = Timeline({"theme": ThemeType.LIGHT})
f = open("D:/BaiduNetdiskDownload/资料/资料/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
# 读取数据
data_lines = f.readlines()
f.close()
# 删除数据中第一行无用数据
data_lines.pop(0)
data_dict = {}
# 取出某年各个国家GDP数据,字典套列表套列表
for line in data_lines:
year = int(line.split(',')[0])
country = line.split(',')[1]
gdp = float(line.split(',')[2])/100000000
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# 根据年份进行排序,确保从1960年顺序加到2009年
sort_year_list = sorted(data_dict.keys())
for year in sort_year_list:
# 取GDP降序排列,并且取前八名
data_dict[year].sort(key=lambda element: element[1], reverse=True)
year_data = data_dict[year][0:8]
x_axis = []
y_axis = []
# 将前八名数据分装到x轴,y轴
for country_gdp in year_data:
x_axis.append(country_gdp[0])
y_axis.append(country_gdp[1])
# 构建柱状图对象,对x轴y轴数据进行翻转,确保GDP高的在上面
bar = Bar()
x_axis.reverse()
y_axis.reverse()
bar.add_xaxis(x_axis)
# 标签显示在右侧
bar.add_yaxis("GDP", y_axis, label_opts=opts.LabelOpts(position="right"))
# 设置标题
bar.set_global_opts(
title_opts=opts.TitleOpts(title=f"{year}年全球GDP前八国家"),
)
bar.reversal_axis()
# 将图表添加到时间线中
timeline.add(bar, str(year))
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=True
)
timeline.render("1960-2009年GDP前八名.html")
运行出来的结果如下图所示:
可以看到在图中右侧,各个年份的坐标全部重叠在一起。
求助大佬们!