Python畫玫瑰圖

第一步,讀取數據;

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', )
# 取C得值畫玫瑰圖
pdat = jsonGlobal.iloc[2, 2:]
pdat

在這裏插入圖片描述

第二步,設置柱長;

# len就是我們極座標的每個柱子的長度
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') #設置極座標的起點(即0度)在正上方向   
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',  # this parameter is a trick
            alpha = 1, 
            fontweight = 'bold', size = 10) 

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章