首页 > 解决方案 > python中的多个饼图尺寸错误

问题描述

我有python中的字典:

dict = {1: {'A': 11472, 'C': 8405, 'T': 11428, 'G': 6613}, 2: {'A': 11678, 'C': 9388, 'T': 10262, 'G': 6590}, 3: {'A': 2945, 'C': 25843, 'T': 6980, 'G': 2150}, 4: {'A': 1149, 'C': 24552, 'T': 7000, 'G': 5217}, 5: {'A': 27373, 'C': 3166, 'T': 4494, 'G': 2885}, 6: {'A': 19300, 'C': 4252, 'T': 7510, 'G': 6856}, 7: {'A': 17744, 'C': 5390, 'T': 7472, 'G': 7312}}

这本词典有 7 个子词典,每个子词典有 4 个条目。我正在尝试在同一个图中制作 7 个饼图(多图),每个坑图都有 4 个部分。绘制我使用以下函数的数据。

def plot(array):
    array = np.array([list(val.values()) for val in dict.values()])
    df = pd.DataFrame(array, index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w', 'd', 't', 'u'])
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    fig, axes = plt.subplots(1,4, figsize=(10,5))
    for ax, col in zip(axes, df.columns):
        ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    axes[0].legend(bbox_to_anchor=(0, 0.5))
    fig.savefig('plot.pdf')
    plt.show()

但是这个函数返回一个带有 4 个饼图的图形,每个饼图有 7 个部分。如果我替换“索引”和“列”,我将得到以下信息error

ValueError: Shape of passed values is (4, 7), indices imply (7, 4)

你知道我该如何解决吗?这是我将得到的数字,但不正确。

在此处输入图像描述

标签: pythonmatplotlib

解决方案


有两个问题:

  • 您想要 7 个子图,但您只使用plt.subplots(1,4). 您应该定义(1,7)有 7 个子图。

  • 您需要相应地重塑数据。由于您需要 7 个饼图,每个饼图有 4 个条目,因此您需要重新调整数组的形状以使其形状为(4, 7)

PS:我使用matplotlib 2.2.2'axes.color_cycle'是折旧的地方。

以下是您修改后的plot功能。


def plot():
    array = np.array([list(val.values()) for val in dict.values()]).reshape((4, 7))
    df = pd.DataFrame(array, index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w', 'd', 't', 'u'])
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    fig, axes = plt.subplots(1,7, figsize=(12,8))
    for ax, col in zip(axes, df.columns):
        ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    axes[0].legend(bbox_to_anchor=(0, 0.5))

在此处输入图像描述


推荐阅读