余姿函的學習歷程 - 大數據 - 10.徑向柱圖 |
|
|
10.徑向柱圖import pandas as pd import matplotlib.pyplot as plt import numpy as np # 生成資料 df = pd.DataFrame( { 'Name': ['item ' + str(i) for i in list(range(1, 51)) ], 'Value': np.random.randint(low=10, high=200, size=50) }) # 排序 df = df.sort_values(by=['Value']) # 初始化畫布 plt.figure(figsize=(20, 10)) ax = plt.subplot(111, polar=True) plt.axis('off') # 設定圖表引數 upperLimit = 100 lowerLimit = 30 labelPadding = 4 # 計算最大值 max = df['Value'].max() # 資料下限10, 上限100 slope = (max - lowerLimit) / max heights = slope * df.Value + lowerLimit # 計算條形圖的寬度 width = 2*np.pi / len(df.index) # 計算角度 indexes = list(range(1, len(df.index)+1)) angles = [element * width for element in indexes] # 繪製條形圖 bars = ax.bar( x=angles, height=heights, width=width, bottom=lowerLimit, linewidth=2, edgecolor="white", color="#33A8FF", ) # 新增標籤 for bar, angle, height, label in zip(bars,angles, heights, df["Name"]): # 旋轉 rotation = np.rad2deg(angle) # 翻轉 alignment = "" if angle >= np.pi/2 and angle < 3*np.pi/2: alignment = "right" rotation = rotation + 180 else: alignment = "left" # 最後新增標籤 ax.text( x=angle, y=lowerLimit + bar.get_height() + labelPadding, s=label, ha=alignment, va='center', rotation=rotation, rotation_mode="anchor")
|
|
中華科技大學數位化學習歷程 - 意見反應 |