使用pyecharts绘制动态GDP柱状图

from pyecharts.charts import *
from pyecharts.options import *
from pyecharts.globals import *

#导入文件数据
f = open("1960-2019全球GDP数据.csv","r",encoding="GB2312")
#取每行数据
data_lines = f.readlines()
#关闭文件
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,国家和gdp构成列表作为value
    try:
        data_dict[year].append([country,gdp])
    except KeyError:
        data_dict[year] = []
        data_dict[year].append([country, gdp])
#按年份从小到大排序
sorted_year_list = sorted(data_dict.keys())
#创建一个时间轴
timeline = Timeline(
    {"theme":ThemeType.LIGHT}
)
#遍历每一年,1960-2019
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 data in year_data:
        x_data.append(data[0])
        y_data.append(data[1]/100000000)#按亿为单位
    #将取到的前八个数据翻转为从小到大
    x_data.reverse()
    y_data.reverse()
    #创建柱状图
    bar=Bar()
    #传入x轴数据
    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="%s年全球前八GDP数据"%year)
    )
    timeline.add(bar,str(year))
timeline.add_schema(
    play_interval=500,       #变化间隔
    is_timeline_show=True,    #显示时间
    is_loop_play=True,        #循环变化
    is_auto_play=True         #自动播放
)
timeline.render("动态GDP柱状图.html")             #绘图

部分效果如下

在这里插入图片描述

1960-2019全球GDP数据.csv

网盘资料链接:1960-2019全球GDP数据.csv
提取码:1234

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值