python數(shù)據(jù)可視化(全球GDP動(dòng)態(tài)柱狀圖開(kāi)發(fā))
開(kāi)發(fā)工具:pycharm、pyecharts模塊
(項(xiàng)目數(shù)據(jù)見(jiàn)文末參考內(nèi)容)
"""
演示GDP動(dòng)態(tài)柱狀圖開(kāi)發(fā)
"""
from pyecharts.charts import Bar,Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
# 讀取數(shù)據(jù)
f = open("資料/資料/可視化案例數(shù)據(jù)/動(dòng)態(tài)柱狀圖數(shù)據(jù)/1960-2019全球GDP數(shù)據(jù).csv", "r", encoding="GB2312")
data_lines = f.readlines()
# 關(guān)閉文件
f.close()
# 刪除第一條數(shù)據(jù)
data_lines.pop(0)
# 將數(shù)據(jù)轉(zhuǎn)換為字典存儲(chǔ),格式為:
# {1960:[[美國(guó),123],[中國(guó),321],......],1961:[[美國(guó),123],[中國(guó),321],......]...}
# 先定義一個(gè)字典,將數(shù)據(jù)按格式存儲(chǔ)字典對(duì)象內(nèi)部
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0]) # 年份
country = line.split(",")[1] # 國(guó)家
gdp = float(line.split(",")[2]) # gdp數(shù)據(jù)
try: # 如果字典有該年份的列表元素,則追加,否則創(chuàng)建一個(gè)空的再追加
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# 創(chuàng)建時(shí)間線對(duì)象
timeline = Timeline({"theme":ThemeType.LIGHT})
# 排序年份
# for循環(huán)每一年的數(shù)據(jù),基于每一年的數(shù)據(jù),創(chuàng)建每一年的bar對(duì)象
# 在for中,將每一年的bar對(duì)象添加到時(shí)間線中
sorted_year_list = sorted(data_dict.keys())
for year in sorted_year_list:
data_dict[year].sort(key = lambda element:element[1], reverse=True)
# 取出本年份Top8的國(guó)家的數(shù)據(jù)
year_data = data_dict[year][0:8]
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0]) # x軸添加國(guó)家
y_data.append(country_gdp[1]) # y軸添加gdp數(shù)據(jù)
# 構(gòu)建柱狀圖
bar = Bar()
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP(億)", y_data, label_opts=LabelOpts(position="right"))
# 反轉(zhuǎn)x軸和y軸
bar.reversal_axis()
# 設(shè)置每一年的圖表的標(biāo)題
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球前8GDP數(shù)據(jù)")
)
timeline.add(bar, str(year))
# 設(shè)置時(shí)間線自動(dòng)播放
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 繪圖
timeline.render("1960-2019全球GDP前8國(guó)家.html")
效果圖如下(輪播1960-2019年的柱狀圖):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-479745.html
參考內(nèi)容:
項(xiàng)目數(shù)據(jù)(https://mp.csdn.net/mp_download/manage/download/UpDetailed)
python語(yǔ)法-pyecharts
黑馬程序員-python基礎(chǔ)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-479745.html
到了這里,關(guān)于python語(yǔ)法-數(shù)據(jù)可視化(全球GDP動(dòng)態(tài)柱狀圖開(kāi)發(fā))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!