Python学习笔记-动态柱状图案例

本文介绍了如何使用Python的sort方法对列表进行排序,以及如何处理和可视化1960-2019年全球GDP数据,通过Pyecharts库实现动态柱状图展示各国GDP排名。
摘要由CSDN通过智能技术生成

使用sort方法对列表内容进行排序

语法:
在这里插入图片描述

my_list = [['a', 23], ['c', 43], ['b', 34]]


def choose_sort_key(element):
    return element[1]


my_list.sort(key=choose_sort_key, reverse=True)
print(my_list)


my_list.sort(key=lambda element: element[1], reverse=False)
print(my_list)
============================================
>>> [['c', 43], ['b', 34], ['a', 23]]
>>> [['a', 23], ['b', 34], ['c', 43]]

案例

案例需求:
在这里插入图片描述
数据格式:(包含1960-2019全球所有国家的gdp)
在这里插入图片描述
第一步:读取文件
逐行读取数据,以列表形式保存在data_lines

# 读取数据
f = open("***\\1960-2019全球GDP数据.csv", 'r', encoding="GB2312")
data_lines = f.readlines()
f.close()

第二步:数据处理

  • 删除第一行
data_lines.pop(0)
  • 将字典转换为字典存储:格式为:
  • #{年份:[[国家1, GDP], [国家2, GDP], …], 年份:[[国家1, GDP], [国家2, GDP], …], …}
data_dict = {}
for line in data_lines:
    year = int(line.split(',')[0])
    country = line.split(",")[1]
    gdp = float(line.split(",")[2])

👆遍历每一行,获取年份,国家,gdp

    try:
        data_dict[year].append([country, gdp])
    except KeyError:
        data_dict[year] = []
        data_dict[year].append([country, gdp])

👆将数据添加到字典中

  • 下一步按照gdp数值对数据排序,取出前八的数据内容
sorted_year = sorted(data_dict.keys())
for year in sorted_year:
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    # 取出前8
    year_data = data_dict[year][0:8]
  • 下一步,将国家和gdp封装到列表中,作为x,y坐标数值
x_data = []
    y_data = []
    for country_gdp in year_data:
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1]/100000000)

下一步,构建柱状图:

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

    bar = Bar()
    x_data.reverse()
    y_data.reverse()
    bar.add_xaxis(x_data)
    bar.add_yaxis('GDP(亿)', y_data, label_opts=LabelOpts(position='right'))
    bar.reversal_axis()
    # 设置每一年的图表标题
    bar.set_global_opts(title_opts=TitleOpts(title=f'{year}年全球前八GDP数据'))
    timeline.add(bar, str(year))
  • 下一步设置自动播放,绘图
# 设置自动播放
timeline.add_schema(
    play_interval=1000,
    is_auto_play=True,
    is_timeline_show=True,
    is_loop_play=False
)
timeline.render('动态.html')

完整代码如下:

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

# 读取数据
f = open('D:\Desktop\Dr\py-lesson\\1960-2019全球GDP数据.csv', 'r', encoding="GB2312")
data_line = f.readlines()
f.close()
# 去除首行
data_line.pop(0)
# print(data_line)
timeline = Timeline()
# 遍历数据并保存在字典中
data_dict = {}
for line in data_line:
    year = int(line.split(',')[0])
    country = line.split(',')[1]
    gdp = float(line.split(',')[2])
    try:
        data_dict[year].append([country, gdp])
    except KeyError:
        data_dict[year] = []
        data_dict[year].append([country, gdp])
# print(data_dict)
sorted_year = sorted(data_dict.keys())
# print(sorted_year)
for year in sorted_year:
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    year_data = data_dict[year][0:8]
    x_data = []
    y_data = []
# print(year_data)
    for country_gdp in year_data:
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1]/100000000)

    # 构建Bar对象
    bar = Bar()
    x_data.reverse()
    y_data.reverse()
    bar.add_xaxis(x_data)
    bar.add_yaxis('GDP(亿)', y_data, label_opts=LabelOpts(position='right'))
    bar.reversal_axis()
    bar.set_global_opts(title_opts=TitleOpts(title=f'{year}年全球前八GDP数据'))
    timeline.add(bar, str(year))

timeline.add_schema(
    play_interval=3000,
    is_loop_play=False,
    is_timeline_show=True,
    is_auto_play=True
)
timeline.render('dt.html')

最终在生成的dt.html文件中,通过浏览器打开图片

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值