强大的经济对一个国家的发展来说,至关重要。在学习了数据可视化,尤其是Matplotlib的基本知识后,我们可以尝试将存在于纸面上与经济相关的数字用直观的图形表示出来,并能从中看出一个国家发展的走势。在本案例中,我们使用新加坡的收支情况和GDP数据集,循序渐进,完成可视化的任务。

1. 数据集概述

数据集描绘了从1986年到2016年底新加坡这个国家的经济发展情况。收支情况数据集有124个样本,3个特征。每个样本表示每个季度的收支情况数据。特征的主要介绍如下:

特征 含义
D Overall Balance (A-B+C) 总收支
Goods Balance 物品的收支
Services Balance 服务的收支

其中,

A B C D
Current Account Balance Capital & Financial Account Balance Net Errors & Omissions Overall Balance

GDP数据集有124个样本,3个特征。每个样本表示每个季度的GDP统计数据,特征的主要介绍如下:

特征 含义
Gross Domestic Product At 2010 Market Prices GDP(以2010年的市场价格计算)
Goods Producing Industries 制造业GDP
Services Producing Industries 服务业GDP

2. 可视化总收支变动情况

从1986年到2016年的31年间,世界发生了天翻地覆的变化,经济的发展斗转千回,有高速的发展,也有泡沫的破灭,危机的降临。下面尝试使用折线图,将31年间新加坡的总收支变动情况可视化。

使用pyplot的编程风格,绘制折线图,展示从1986年到2016年间新加坡政府的总收支(Balance)情况:

  • 数据集已经导入,命名为df_balance,类型为DataFrame,数据的索引为具体的年份季度,比如1986 Q1

  • 图形X轴代表的是df_balance的索引取值;Y轴代表的是数据集特征D Overall Balance (A-B+C)的数据。

  • 图形的细节要求为:

图形元素 取值 字体大小
title Overall Balance for Singapore from 1986 to 2016 18
xlabel Year/Quarter 15
ylabel Balance 15
  • 在线编程环境已经默认开启matplotlib line模式,无需使用show()函数展示图形。

  • 图形的其他参数保持默认值。

In [27]:
## 参考代码
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df_balance = pd.read_csv('./input/singapore.csv', index_col = 0)
x_indexes = df_balance.index.values
x_values = range(len(x_indexes))
y_values = df_balance['D Overall Balance (A-B+C)']

fig = plt.figure(figsize = (10, 8))
plt.title('Overall Balance for Singapore from 1986 to 2016', fontsize = 18)
plt.xticks(x_values, x_indexes)
plt.xlabel('Year/Quarter', fontsize = 15)
plt.ylabel('Balance', fontsize = 15)
plt.grid(axis = 'y', color = 'grey', linestyle = '--', lw = 0.5, alpha = 0.5)
plt.plot(x_values, y_values)
Out[27]:
[<matplotlib.lines.Line2D at 0x7fc9bfd51550>]

3. 调整收支情况折线图

从折线图中,我们可以知道,新加坡的经济经历了起起伏伏,虽然经常出现赤字,但情况总体趋好。然而,由于X轴的刻度标签过密,我们无法准确解释折线的变动情况。因此,我们需要对折线图进行调整,重点是重新设置X轴的刻度以及标签。

本题采用混合的编程风格,重新绘制折线图。

新增要求如下:

  • 调整X轴的主刻度间隔为4;副刻度间隔为1。

  • 更改X轴的刻度标签,只显示年份,不显示具体的季度。

  • 去掉图形四周的边框。

  • 图形增加图例。

  • 图形细节的具体要求为:

图形的元素 取值 字体大小
X轴代表的数据 df_balance的索引值 -
Y轴代表的数据 特征D Overall Balance (A-B+C)的数据 -
title Overall Balance for Singapore from 1986 to 2016 20
xlabel Year 18
ylabel Balance 18
X轴刻度取值范围 [1, 数据集的行数] -
  • 在线编程环境已经默认开启matplotlib line模式,无需使用show()函数展示图形。

  • 图形的其他参数保持默认值。

In [28]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline

df_balance = pd.read_csv('./input/singapore.csv', index_col = 0)

fig, ax = plt.subplots()
fig.set_figwidth(10)
fig.set_figheight(8)

# 获取df_balance的大小
rows, col = df_balance.shape

# 获取df_balance的大小
rows, col = df_balance.shape

# X轴的数据为从1到len(rows)的整数序列
x_values = np.arange(rows) + 1

# Y轴的数据为收支情况
y_values = df_balance['D Overall Balance (A-B+C)']

# 添加标题
ax.set_title('Overall Balance for Singapore from 1986 to 2016', fontsize = 20)

# 添加Y轴标题
ax.set_xlabel('Year', fontsize = 18)
ax.set_ylabel('Balance', fontsize = 18)

# 添加背景网格
ax.grid(axis='y',color='grey', linestyle='--', lw = 0.5, alpha = 0.5)

# 图形四周去掉边框
for item in ax.spines.values():
    item.set_visible(False)

# 设置图形X轴的刻度范围[1, rows]
ax.set_xlim(1, rows)

# 设置图形X轴的刻度标签,为年份从1987-2016
xlabels = np.arange(1986, 2017, 1)

# 设置图形X轴刻度标签的角度45
ax.set_xticklabels(xlabels, rotation = 45)

# 设置图形X轴刻度的间隔,主刻度为4,副刻度为1
ax.xaxis.set_major_locator(ticker.MultipleLocator(4))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))

# 绘制曲线图, 参数label取值为Singapore
ax.plot(x_values, y_values, label = 'Singapore')

# 添加图例,图例的位置在左上方, 字体大小为12
ax.legend(loc = 'upper left', shadow = True, fontsize = 12)
Out[28]:
<matplotlib.legend.Legend at 0x7fc9bf2d2048>

4. 绘制多条曲线

重新绘制的折线图可以告诉我们,图中的三个低点分别对应于1998年,2008年以及2016年。事实上,新加坡在98年的金融危机,08年的次贷危机深受波及,反应在收支情况上,出现赤字。而2016年,更是新加坡的经济困难时期。

现在,我们希望同时观察到随着时间的推移,制造业和服务业收支的变动情况。

我们在使用Matpltolib进行绘图的时候,可以在同一幅图形上添加多条曲线。现在,我们根据美化调整过的曲线图型模板(如上题),绘制一幅展示Goods BalanceServices Balance之间走势的折线图形。这幅图形包含两条曲线,它们共享X轴,拥有自己的Y轴。

  • 使用混合的编程风格绘制图形。

  • 图形细节的具体要求为:

图形的元素 取值 字体大小
图形的大小 (10, 10) -
X轴代表的数据 df_balance的索引值 -
左Y轴代表的数据 特征Goods Balance的数据 -
右Y轴代表的数据 特征Services Balance的数据 -
title Goods and Services Balance of Singapore from 1986 to 2016 20
xlabel Year 18
左Y轴的ylabel Goods Balance 18
右Y轴的ylabel Services Balance 18
X轴刻度的取值范围 [1, 数据集的行数] -
Goods Balance曲线颜色 b -
Services Balance曲线颜色 r -
  • 在线编程环境已经默认开启matplotlib line模式,无需使用show()函数展示图形。

  • 图形的其他参数保持默认值。

In [29]:
## 参考代码
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline

df_balance = pd.read_csv('./input/singapore.csv', index_col = 0)
rows, col = df_balance.shape
x_values = np.arange(rows) + 1
y_values_goods = df_balance['Goods Balance']
y_values_service = df_balance['Services Balance']

fig, ax = plt.subplots(figsize=(10, 8)) 
ax.grid(axis = 'y', color = 'grey', linestyle = '--', lw = 0.5, alpha = 0.5)
ax.plot(x_values, y_values_goods, 'b', label='Goods')

ax.set_title('Goods and Services Balance of Singapore from 1986 to 2016', fontsize = 20)
ax.set_ylabel('Goods Balance', fontsize = 18)
ax.set_xlim(1, rows)
xlabels = np.arange(1986, 2017, 1)

ax1 = ax.twinx()
ax1.plot(x_values, y_values_service, 'r', label = 'Services')
ax1.set_ylabel('Services Balance', fontsize = 18)

fig.legend(loc = 'upper left', fontsize = 15, bbox_to_anchor=(0, 1), bbox_transform=ax.transAxes)
ax.set_xticklabels(xlabels, rotation = 45)
ax.xaxis.set_major_locator(ticker.MultipleLocator(4))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1))

for axes in [ax, ax1]:
    for item in axes.spines.values():
        item.set_visible(False)

5. 探索GDP与收支情况变动

现在,我们加入新加坡从1986年到2016年的GDP数据数据集,探索GDP和收支情况之间的关系。

本题基于收支情况数据集和GDP数据集,绘制散点图:

  • 收支情况数据集已经导入,保存为变量df_balance,数据的索引为具体的年份季度,比如1986 Q1

  • GDP数据集已经导入,保存为变量df_gpd,数据的索引为具体的年份季度,比如1986 Q1

  • 使用混合的编程风格,绘制一个$1 \times 2$的散点图矩阵。

  • 图形的大小为(10, 5)。

  • 图形的标题为GDP vs Balance, 字体大小为15。

  • 左子图的具体要求为:
图形的元素 取值 字体大小
X轴代表的数据 特征Goods Producing Industries的数据 -
Y轴代表的数据 特征Goods Balance的数据 -
右Y轴代表的数据 特征Services Balance的数据 -
title Goods 默认值
xlabel Goods Producing Industries 默认值
ylabel Goods Balance 默认值
  • 右子图的具体要求为:
图形的元素 取值 字体大小
X轴代表的数据 特征Services Producing Industries的数据 -
Y轴代表的数据 特征Services Balance的数据 -
title Services 默认值
xlabel Services Producing Industries 默认值
ylabel Services Balance 默认值
  • 使用subplots_adjust()函数调整两个子图之间的距离,参数hspace的值为0.1,参数wspace的值为0.3。

  • 在线编程环境已经默认开启matplotlib line模式,无需使用show()函数展示图形。

  • 图形的其他参数保持默认值。

In [30]:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df_balance = pd.read_csv('./input/singapore.csv', index_col = 0)
df_gdp = pd.read_csv('./input/singapore_gdp.csv', index_col = 0)
df_data = pd.concat([df_balance, df_gdp], axis = 1)
titles = ['Goods', 'Services']
xlabels = ['Goods Producing Industries', 'Services Producing Industries']
ylabels = ['Goods Balance', 'Services Balance']
x_values = [df_data[item] for item in xlabels]
y_values = [df_data[item] for item in ylabels]

fig, axes = plt.subplots(1,2, figsize = (16, 6))
for ax, x, y, title, label_x, label_y in zip(axes, x_values, y_values, titles, xlabels, ylabels):    
    ax.scatter(df_data[label_x], df_data[label_y])
    ax.set_title(title)
    ax.set_xlabel(label_x)
    ax.set_ylabel(label_y)
fig.subplots_adjust(hspace=0.1, wspace = 0.3)
fig.suptitle('GDP vs Balance', fontsize = 15)
Out[30]:
Text(0.5, 0.98, 'GDP vs Balance')