Python实现动态GDP显示

该文章介绍了如何利用Python的pyecharts库,结合Echarts的时间线功能,动态展示1960-2019年间全球GDP数据。首先,从CSV文件中读取并处理数据,然后创建一个时间线对象,并为每一年生成柱状图,展示当年GDP前八的国家。最后,配置时间线属性并渲染为HTML页面,实现自动播放的GDP变化图表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python实现GDP动态显示

数据资料本人在网上自己下载

根据需求导入模块

from pyecharts.charts import Bar, Timeline   
from pyecharts.options import *
from pyecharts.globals import ThemeType

#读取数据
f = open("G:/资料/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
#关闭文件
f.close()
#删除第一条数据
data_lines.pop(0)
#将数据转化为字典储存,格式为
#{ 年份:[ [国家, gdp], [国家, gpd], ....... ], 年份:[ [国家, gdo], [国家, gpd], ...... ], ......}

#定义字典对象
data_dict = {}
for line in data_lines:
    year = int(line.split(",")[0])  #年份
    country = line.split(",")[1]    #国家
    gdp = float(line.split(",")[2]) #gdp数据
    #如何判断字典有没有指定的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())
for year in sorted_year_list:
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    #取出本年份前八名的国际
    year_data = data_dict[year][0:10]
    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_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))


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

#设置时间线自动播放
timeline.add_schema(
    play_interval=200,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=False
)
# 绘图
timeline.render("1960-2019全球GDP前8国家.html")

运行之后会生成html网页
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eglike

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值