import pygal,json
with open('gdp_json.json', 'r') as f:
gdp_data = json.load(f)
#print(gdp_data[0])
#只分析5個國家的
country_name = ['中國','美國','日本','俄羅斯','加拿大']
country_codes = ['CHN','USA','JPN','RUS','CAN']
country_gdp_codes = [{},{},{},{},{}]
for gdp_item in gdp_data:
for i,country in enumerate(country_codes):
if gdp_item['Country Code'] == country:
year = gdp_item['Year']
if 2000 < year < 2017:
country_gdp_codes[i][year] = gdp_item['Value']
#print(country_gdp_codes)
#轉換country_gdp_codes成pygal所需的數據格式
country_gdp_list = [[],[],[],[],[]]
xdata = range(2001,2017)
for i in range(len(country_gdp_list)):
for year in xdata:
country_gdp_list[i].append(country_gdp_codes[i][year] / 1e8)
print(country_gdp_list)
#柱狀圖展示
bar = pygal.Bar()
bar.title = '五國GDP_2001-2016'
#添加數據
for i,item_name in enumerate(country_name):
bar.add(item_name,country_gdp_list[i])
#配置
bar.x_labels = xdata
bar.x_title = '年份'
bar.y_title = 'GDP(億)'
bar.x_label_rotation = 45
bar.legend_at_bottom = True
bar.show_y_guides = True
bar.show_x_guides = True
#輸出到圖片
bar.render_to_file("gdp.svg")
附:GDP資源json文件,如需要可以私信我,我發給您。不知道爲啥,不讓上傳。