第一步,讀取數據;
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
jsonGlobal = pd.read_excel('E:/BaiduNetdiskDownload/Tableau課程所用數據/玩家綜合能力雷達圖數據.xlsx', )
pdat = jsonGlobal.iloc[2, 2:]
pdat
第二步,設置柱長;
pdat = pd.DataFrame({'value':pdat, 'len':1.2 ** (pdat+1)})
pdat
第三步,設置角度;
l = pdat['len']
N = pdat.shape[0]
width = 2*np.pi/N
rad = np.cumsum([width]* N) - width/2
rad
第四步,設置顏色
import matplotlib as mpl
cm = mpl.cm.get_cmap('Reds')
colors = cm((rad - rad.min())/ (rad.max()-rad.min()))
colors
第五步,做圖;
普通型
plt.figure(figsize = (6, 8))
ax = plt.subplot(projection = 'polar')
ax.bar(rad, l, width = width, color = colors, alpha = 1)
中央空白型
plt.figure(figsize = (6, 8))
ax = plt.subplot(projection = 'polar')
ax.set_ylim(-1,np.ceil(l.max())+1)
ax.bar(rad, l, width = width, color = colors, alpha = 1)
半透明型
plt.figure(figsize = (6, 8))
ax = plt.subplot(projection = 'polar')
ax.bar(rad,1,width = width,color = colors, alpha=0.5)
第六步,添加標籤,美化圖形。
txt_settings = {
'span':{0:0.5, 1:0.5, 2:0.5, 3: 0.5},
'color':{0:'black', 1:'black', 2:'black', 3: 'black'},
'rot_adj' : {0:-90, 1: -90, 2: 90, 3:90},
'ha':{0:'right', 1: 'right',2:'left',3: 'left'}
}
txt_label = ['{} {}'.format(x, y)
for x, y in zip(pdat.index, pdat['value'])]
plt.figure(figsize = (6,8))
ax = plt.subplot(projection = 'polar')
ax.set_ylim(-1,np.ceil(l.max()) + 1)
ax.set_theta_zero_location('N')
ax.grid(False)
ax.spines['polar'].set_visible(False)
ax.set_yticks([])
ax.set_thetagrids([])
bars = ax.bar(rad,l,width = width, color = colors, alpha = 1)
ax.bar(rad,1,width = width,color = 'white', alpha = 0.3)
ax.bar(rad,1.5,width = width, color = 'white', alpha = 0.2)
for i in np.arange(N):
direc = rad[i]//(np.pi/2)
ax.text(rad[i],
l[i] + txt_settings['span'][direc] ,
txt_label[i],
rotation = rad[i] * 180 /np.pi + txt_settings['rot_adj'][direc],
color = txt_settings['color'][direc],
ha = txt_settings['ha'][direc], va = 'center',
rotation_mode = 'anchor',
alpha = 1,
fontweight = 'bold', size = 10)