pyecharts制作gdp动态柱形图-学习记录
python-黑马程序员
"""
GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
# 读取数据
f = open(r"第1-12章资料\资料\可视化案例数据\动态柱状图数据\1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
f.close()
# 删除第一条数据(列名)
data_lines.pop(0)
# print(data_lines)
# 将数据转换为字典存储
# {1960:[[中国, 123], [美国,234]...], 1961:[[中国, 223], [美国,334]...], ...}
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0])
country = line.split(",")[1]
gdp = round(float(line.split(",")[2])) # float会自动去掉空格
try: # year已存在
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# print(data_dict)
# 排序年份 字典的key是无序的
sorted_year_list = sorted(data_dict.keys())
# print(sorted_year_list)
# 创建时间线对象
timeline = Timeline(
{"theme": ThemeType.LIGHT}
)
for year in sorted_year_list:
data_dict[year].sort(key= lambda element:element[1], reverse=True) # 按gdp降序
# 取出本年份前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(round(country_gdp[1]/100000000, 0)) # y轴gdp
# 构建柱状图
bar = Bar()
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数据")
)
bar.render(f"动态图/{year}.html") # 单帧无时间线的留存一份,用于生成gif
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-2019全球GDP前8国家.html")
html可查看带时间线的动图。
希望将其保存为gif。
所以先将所有年份的柱状图(不带时间线)html逐个保存,通过selenium访问html,并截图为png。
这样拥有了所有年份的逐帧图片,最后用imageio保存为动图。
import time
from selenium import webdriver
import imageio
driver = webdriver.Edge()
images = []
for year in range(1960, 2020):
# Open the HTML file in the browser and take a screenshot
driver.get(f"file:///e:/python黑马学习/动态图/{year}.html")
time.sleep(1) # Wait for the chart to render
screenshot = driver.get_screenshot_as_png()
images.append(imageio.imread(screenshot))
driver.quit()
# Save the images as a GIF
imageio.mimsave("动态图/1960-2019全球GDP前8国家.gif", images, duration=1, loop=0)
问题:
mimsave中设置duration=1,应该是1秒播1帧,但是gif播放速度实际很快,最后用Ezgif - free online animated GIF editor设置的播放速度。
效果如图: