You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
4.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import matplotlib.pyplot as plt
# 创建图形和坐标轴对象指定尺寸和DPI
fig, ax = plt.subplots(figsize=(13.33,7.5), dpi = 96)
# 绘制折线
for country in top_20_countries:
data = df[df['Country Name'] == country]
line = ax.plot(data['Year'], data['GDP'], label=country)
# 添加图例
ax.legend(loc="best", fontsize=8)
# 创建网格
ax.grid(which="major", axis='x', color='#DAD8D7', alpha=0.5, zorder=1)
ax.grid(which="major", axis='y', color='#DAD8D7', alpha=0.5, zorder=1)
# 重新格式化x轴标签和刻度线标签
ax.set_xlabel('', fontsize=12, labelpad=10)
# 不需要轴标签
ax.xaxis.set_label_position("bottom")
ax.xaxis.set_major_formatter(lambda s, i : f'{s:,.0f}')
#以防万一我们需要额外的格式设置
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
#以防我们需要额外的格式化
ax.xaxis.set_tick_params(pad=2, labelbottom=True, bottom=True, labelsize=12, labelrotation=0)
# 重新格式化y轴
ax.set_ylabel('GDP (Billions USD)', fontsize=12, labelpad=10)
ax.yaxis.set_label_position("left")
ax.yaxis.set_major_formatter(lambda s, i : f'{s*10**-9:,.0f}')
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
#以防我们需要额外的格式化
ax.yaxis.set_tick_params(pad=2, labeltop=False, labelbottom=True, bottom=False, labelsize=12)
# 颜色和线条样式
colors_dict = {'United States': '#014f86', 'China': '#DC0000', 'Japan': '#ff4d6d', 'Germany': '#403d39', 'India': '#6a994e'}
line_styles_dict = {'United States': '-', 'China': '-', 'Japan': '-', 'Germany': '-', 'India': '-'}
# 绘制前5条线
for country in top_20_countries[:5]:
color = colors_dict.get(country, 'grey')
# 从字典中获取颜色,如果找不到,默认为灰色
line_style = line_styles_dict.get(country, '-')
# 从字典中获取线条样式,如果未找到,默认为实线
data = df[df['Country Name'] == country]
line = ax.plot(data['Year'], data['GDP'], color=color, linestyle=line_style, zorder=2, label=country)
# 添加图例
ax.legend(loc="best", fontsize=8)
# 绘制剩余部分
for country in top_20_countries[5:]:
data = df[df['Country Name'] == country]
line = ax.plot(data['Year'], data['GDP'], color='grey', linestyle=':', linewidth=0.5, zorder=2)
# 移除边框
ax.spines[['top','right','bottom']].set_visible(False)
# 加粗左侧边框
ax.spines['left'].set_linewidth(1.1)
# 在顶部添加红线和矩形
ax.plot([0.05, .9], [.98, .98], transform=fig.transFigure, clip_on=False, color='#E3120B', linewidth=.6)
ax.add_patch(plt.Rectangle((0.05,.98), 0.04, -0.02, facecolor='#E3120B', transform=fig.transFigure, clip_on=False, linewidth = 0))
# 添加标题和副标题
ax.text(x=0.05, y=.93, s="Evolution of the 20 Richest Countries GDP over the Past 50 Years", transform=fig.transFigure, ha='left', fontsize=14, weight='bold', alpha=.8)
ax.text(x=0.05, y=.90, s="Focus on the current 5 richest countries from 1973 to 2022", transform=fig.transFigure, ha='left', fontsize=12, alpha=.8)
# 设置来源文本
ax.text(x=0.05, y=0.12, s="Source: World Bank - https://databank.worldbank.org/", transform=fig.transFigure, ha='left', fontsize=10, alpha=.7)
# 调整绘图区域周围的边距
plt.subplots_adjust(left=None, bottom=0.2, right=None, top=0.85, wspace=None, hspace=None)
# 设置白色背景
fig.patch.set_facecolor('white')
# 绘制前5条线
for country in top_20_countries[:5]:
color = colors_dict.get(country, 'grey')
# 从字典中获取颜色,如果找不到,默认为黑色
line_style = line_styles_dict.get(country, '-')
# 从字典中获取线条样式,如果找不到,默认为实线
data = df[df['Country Name'] == country]
line = ax.plot(data['Year'], data['GDP'], color=color, linestyle=line_style, zorder=2, label = country)
ax.plot(data['Year'].iloc[-1], data['GDP'].iloc[-1], 'o', color=color, markersize=10, alpha=0.3)
ax.plot(data['Year'].iloc[-1], data['GDP'].iloc[-1], 'o', color=color, markersize=5)
# 在图表上添加一些文字
ax.annotate('During the 2000s,\nChina began experiencing rapid economic growth,\noutpacing all other countries.', (data['Year'].iloc[-18], 2000000000000), xytext=(data['Year'].iloc[-28]-timedelta(days=500), 18000000000000), ha='left', fontsize=9, arrowprops=dict(arrowstyle='-|>', facecolor='k', connectionstyle="arc3,rad=-0.15"))