在b站黑马学python,pyecharts画时间线柱状图x轴坐标重复出现并重叠

以下是源代码:

from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType


# 构建时间限定对象
timeline = Timeline({"theme": ThemeType.LIGHT})
f = open("D:/BaiduNetdiskDownload/资料/资料/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
# 读取数据
data_lines = f.readlines()
f.close()
# 删除数据中第一行无用数据
data_lines.pop(0)
data_dict = {}


# 取出某年各个国家GDP数据,字典套列表套列表
for line in data_lines:
    year = int(line.split(',')[0])
    country = line.split(',')[1]
    gdp = float(line.split(',')[2])/100000000
    try:
        data_dict[year].append([country, gdp])
    except KeyError:
        data_dict[year] = []
        data_dict[year].append([country, gdp])


# 根据年份进行排序,确保从1960年顺序加到2009年
sort_year_list = sorted(data_dict.keys())
for year in sort_year_list:
    # 取GDP降序排列,并且取前八名
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    year_data = data_dict[year][0:8]
    x_axis = []
    y_axis = []
    # 将前八名数据分装到x轴,y轴
    for country_gdp in year_data:
        x_axis.append(country_gdp[0])
        y_axis.append(country_gdp[1])

    # 构建柱状图对象,对x轴y轴数据进行翻转,确保GDP高的在上面
    bar = Bar()
    x_axis.reverse()
    y_axis.reverse()
    bar.add_xaxis(x_axis)
    # 标签显示在右侧
    bar.add_yaxis("GDP", y_axis, label_opts=opts.LabelOpts(position="right"))
    # 设置标题
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title=f"{year}年全球GDP前八国家"),
    )
    bar.reversal_axis()
    # 将图表添加到时间线中
    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-2009年GDP前八名.html")

运行出来的结果如下图所示:

可以看到在图中右侧,各个年份的坐标全部重叠在一起。

求助大佬们!

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值