给出四大国有银行2018年相关财务和监管指标的排名(见data.xlsx“第二题”工作表)。要求将4家银行各项指标的排名绘制成雷达图并且以2x2子图的形式显示,效果如图所示。
其中data.xlsx如下:
代码实现如下:(注意看注释)
# coding:utf-8
# 作者: 菜菜林妙妙
'''
当时做的不好的总结:
一开始获取数据十分不熟悉,程序获取数据出错,一直报错 然后解bug,花了大半节课才获取到第一题的数据,
获取数据混乱主要是因为很多学了很多库,导致搞错了参数,因为有很多操作excel文件的库,因此后面我又认真专门学习了pandas的获取方法
其实该题目画图不难,但是一开始的数据花了很多时间,导致后面慌乱,没有设计循环,而是使用冗余的代码
该题目只要设置好循环变量就可以把题目使用精简的代码写出来
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
if __name__ == "__main__":
# 先设置字体,因为本电脑字体缺失
plt.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei', 'FangSong']
plt.rcParams['font.size'] = 12 # 字体大小
plt.rcParams['axes.unicode_minus'] = False
company = ['指标','农业银行','建设银行','工商银行','中国银行']
# 读取文件:
data = pd.read_excel('data.xlsx', sheet_name='第二题', usecols=[1, 2, 3, 4, 5], names=company,header=1)
# 控制图的顺序
for i in range(1,4):
# 交换两列的数据
data[company[i]], data[company[i+1]] = data[company[i+1]], data[company[i]]
print(data)
# 创建画布
fig = plt.figure(figsize=(10,10))
fig.suptitle("四大国有银行2018年相关财务和监管指标的排名")
fig.subplots_adjust(wspace=0.9) # 设置子图间的间距,为子图宽度的80%
# y数据
y = []
# 颜色
color = ['#ff3344','#77ff66','#3399ef','#171aee']
# 维度标签
radar_labels = list(data['指标'])
for i in range(0,len(radar_labels)):
radar_labels[i] = radar_labels[i] + '排名'
print(radar_labels)
# 以下这行可以不需要:因为这边只有6个label,起点和终点不存在显示两次的问题,所以不需要显示两次,就不用以下的代码
radar_labels = np.concatenate((radar_labels, [radar_labels[0]]))
for i in range(4):
y = list(data.iloc[:,i+1]) # data.iloc[]里面:[行:列] 每次取出一列
print(y)
# 画布
ax = fig.add_subplot(2, 2, i + 1, polar=True)
# ax = plt.subplot(22(i+1),polar=True)
# 划线
angles = np.linspace(0, 2 * np.pi, len(y), endpoint=False)
# 为了使他封闭
angles = np.concatenate((angles, [angles[0]]))
# 为了使他封闭
y = np.concatenate((y, [y[0]]))
# 绘制雷达图
ax.plot(angles, y, color='blue',lw=1.0,ls='--')
# 设置极坐标标签
ax.set_thetagrids(angles * 180 / np.pi, labels=radar_labels)
# 设置雷达图的0度起始位置
# ax.set_theta_zero_location('N')
# 设置雷达图的坐标刻度范围
ax.set_rlim(0, 4.02)
# 设置雷达图的坐标值显示角度,相对于起始角度的偏移量
# ax.set_rlabel_position(270)
# 填充多边形
ax.fill(angles, y, alpha=0.25,color=color[i])
ax.set_title(company[i+1])
# 添加中间的0 注意不要漏掉了
ax.text(0,0,'0')
plt.savefig("雷达图.png")
plt.show()
这里注意题目给的图的顺序和要求画的子图顺序不一样,做了一个简单的交换。