利用pyecharts包创建动态柱状图
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts, TitleOpts
from pyecharts.globals import ThemeType
# 数据处理
f = open("Y:/py/itheima/1-12章资料/资料/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines() # 读取每一行的数据
print(data_lines)
# 关闭文件
f.close()
# 删除无用数据
data_lines.pop(0) # 删除第一行
# 将数据转化为字典格式
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0]) # 年份
country = line.split(",")[1] # 国家
gdp = float(line.split(",")[2]) # gdp
# 判断字典中有没有指定的key, 用try , except
try: # 存在key , year
data_dict[year].append([country, gdp])
except KeyError: # 不存在key, year
data_dict[year] = []
data_dict[year].append([country, gdp])
# print(data_dict[1960])
timeline = Timeline({"theme": ThemeType.LIGHT})
# 排序年份
sorted_years = sorted(data_dict.keys())
for year in sorted_years:
data_dict[year].sort(key=lambda element: element[1], reverse=True) # 排序
# 取出前8名国家
year_data = data_dict[year][0:8]
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, 将单位化为亿
# 构建柱状图对象
bar = Bar()
# 将x轴和y轴自身数据反转
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
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,
is_timeline_show=False,
is_auto_play=True,
is_loop_play=False
)
timeline.render("动态GDP.html")