注:本文所用数据均来自百度开源数据
数据会在下方展示下载按钮,请自行提取。
本文需要用到jsonpyecharts模块,请自行在PyCharm中添加。
柱状图演示:Top-8-countries-in-global-GDP – Admin_Log加载可能较慢,请耐心等待◊ヾ(•ω•`)o

Admin_Log

1960~2019全球GDP前8国家

"""
GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType

# 读取数据
f = open("E:/PycharmProjects/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
f.close()
# 删除第一行数据
data_lines.pop(0)
# 将数据转换为字典存储,格式为:
# {年份: [[国家, gdp], [国家, gdp], ...... ], 年份: [[国家, gdp], [国家, gdp]......], ...... }
# 定义字典对象
data_dict = {}
for line in data_lines:
    year = int(line.split(",")[0])
    country = line.split(",")[1]
    gdp = float(line.split(",")[2])
    # 判断字典里面有无指定的key
    try:
        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())
# print(sorted_year_list)
for year in sorted_year_list:
    # 对GDP进行排序
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    # 取出本年份前八名的国家
    year_data = data_dict[year][0:8]
    x_data = []
    y_data = []
    # 利用for循环将国家数据加到X轴,将GDP数据加到Y轴
    for country_gdp in year_data:
        # 将国家添加到X轴
        x_data.append(country_gdp[0])
        # 将GDP添加到Y轴(因单位为“亿”,所以要将GDP数据除以一亿)
        y_data.append(country_gdp[1] / 100000000)
        # 若觉得柱状图中的小数点过多可选择[ y_data.append(country_gdp[1] / 100000000) ]替换上一行即可转换为整数
    # 构建柱状图
    bar = Bar()
    # 默认大值在下,若实现大值在上需要反转国家名,同时也要同步反转数据,否则GDP最低国家会拿到GDP最高国家的数据
    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}年全球前8名GDP数据"),
        # 可添加工具箱方便下载示例图 - [ 放开下行代码注释即可 ]
        # toolbox_opts=ToolboxOpts(is_show=True)
    )
    timeline.add(bar, str(year))

# for循环每一年的数据,基于每一年的数据,创建每一年的bar对象
# 在for循环中,将每一年的bar对象添加到时间线中

# 设置时间线自动播放
timeline.add_schema(
    play_interval=1000,         # 播放间隔时间(ms)毫秒:1000ms = 1s
    is_timeline_show=True,      # 展示时间线:是
    is_auto_play=True,          # 是否自动播放:是
    is_loop_play=False          # 是否循环播放:否
)
# 绘图
timeline.render("1960 - 2019全球GDP前8国家.html")

下载信息

Admin_Log