溫馨提示×

Matplotlib怎么繪制多層次餅圖以表示嵌套數(shù)據(jù)

小億
91
2024-05-21 11:23:32
欄目: 編程語言

要繪制多層次餅圖以表示嵌套數(shù)據(jù),首先需要導入Matplotlib庫。然后,可以使用Matplotlib的pie函數(shù)來繪制基本的餅圖,然后使用遞歸的方法來繪制多層次餅圖。

以下是一個示例代碼,演示如何用Matplotlib繪制多層次餅圖:

import matplotlib.pyplot as plt

# 嵌套數(shù)據(jù)
data = {
    'A': {
        'A1': 10,
        'A2': 20
    },
    'B': {
        'B1': 15,
        'B2': {
            'B2.1': 5,
            'B2.2': 10
        }
    }
}

def draw_pie(data, parent_label='', explode=0.1, depth=0):
    labels = data.keys()
    sizes = [data[label] if type(data[label]) == int else sum(data[label].values()) for label in labels]
    explode = [explode] * len(labels)
    
    plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=140)
    plt.axis('equal')
    
    for label in labels:
        if type(data[label]) == dict:
            draw_pie(data[label], parent_label=label, explode=0.1, depth=depth+1)
            
    plt.title(parent_label)

draw_pie(data)
plt.show()

在這個示例中,我們定義了一個名為draw_pie的函數(shù),用來繪制多層次餅圖。該函數(shù)接受一個嵌套的數(shù)據(jù)字典作為輸入,然后遞歸地繪制每個層次的餅圖。

通過運行這段代碼,可以得到一個包含嵌套數(shù)據(jù)的多層次餅圖,每個層次的數(shù)據(jù)用不同的顏色表示。

0