第一步,读取数据;
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 )