如何做嵌套比例面积图(圆圈)?

How to do a Nested Proportional Area Chart (circles)?

我正在 python 中寻找任何可以用来制作圆圈嵌套比例面积图的东西。最好是使用(或基于)matplotlib 构建的东西。这是一个这样的情节的例子供参考:

嵌套圆图,其中圆面积与数据成正比,如下所示。 它将采用排序列表或数据数组以及可选的相应标签作为输入并绘制几个圆圈。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection


def nested_circles(data, labels=None, c=None, ax=None, 
                   cmap=None, norm=None, textkw={}):
    ax = ax or plt.gca()
    data = np.array(data)
    R = np.sqrt(data/data.max())
    p = [plt.Circle((0,r), radius=r) for r in R[::-1]]
    arr = data[::-1] if c is None else np.array(c[::-1])
    col = PatchCollection(p, cmap=cmap, norm=norm, array=arr)

    ax.add_collection(col)
    ax.axis("off")
    ax.set_aspect("equal")
    ax.autoscale()

    if labels is not None:
        kw = dict(color="white", va="center", ha="center")
        kw.update(textkw)
        ax.text(0, R[0], labels[0], **kw)
        for i in range(1, len(R)):
            ax.text(0, R[i]+R[i-1], labels[i], **kw)
    return col

用法可能类似于

data = [1,3,4,5,6]
labels = list("ABCDE")
nested_circles(data, labels=labels, cmap="copper", textkw=dict(fontsize=14))
plt.show()

如果您想要不同的颜色编码,请使用 c 参数并提供另一个值列表,例如

data = [1,3,4,5,6]
labels = list("ABCDE")
codes = [5,3,1,4,2]
circles = nested_circles(data, labels=labels, c=codes, cmap="plasma", 
                         textkw=dict(color="black", fontsize=14))
plt.colorbar(circles, label="Codes")
plt.title("Diagram")
plt.show()