首页 > 解决方案 > 有没有办法在 matplotlib 热图中绘制饼图?

问题描述

在此处输入图像描述我有一个包含几行和多列的热图。以前,我为每个 (row_index,column_index) 绘制一个圆圈并将这个圆圈附加到一个 circle_list。我正在将 circle_list 作为集合添加到轴中。

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


def heatmap_with_circles(data_array,row_labels,column_labels,ax=None, cmap=None, norm=None, cbar_kw={}, cbarlabel="", **kwargs):

    circles=[]
    for row_index, row in enumerate(row_labels):
        for column_index, column in enumerate(column_labels):
            circles.append(plt.Circle((row_index,column_index),radius=0.4))

    col = PatchCollection(circles, array=data_array.flatten(), cmap=cmap, norm=norm)
    ax.add_collection(col)

    # We want to show all ticks...
    ax.set_xticks(np.arange(data_array.shape[1]))
    ax.set_yticks(np.arange(data_array.shape[0]))

    fontsize=10
    ax.set_xticklabels(column_labels, fontsize=fontsize)
    ax.set_yticklabels(row_labels, fontsize=fontsize)

    #X axis labels at top
    ax.tick_params(top=True, bottom=False,labeltop=True, labelbottom=False,pad=5)
    plt.setp(ax.get_xticklabels(), rotation=55, ha="left", rotation_mode="anchor")

    # We want to show all ticks...
    ax.set_xticks(np.arange(data_array.shape[1]+1)-.5, minor=True)
    ax.set_yticks(np.arange(data_array.shape[0]+1)-.5, minor=True)

    ax.grid(which="minor", color="black", linestyle='-', linewidth=3)
    ax.tick_params(which="minor", bottom=False, left=False)


data_array=np.random.rand(3,4)
row_labels=['Row1', 'Row2', 'Row3']
column_labels=['Column1', 'Column2', 'Column3','Column4']

fig, ax = plt.subplots(figsize=(1.9*len(row_labels),1.2*len(column_labels)))
ax.set_aspect(1.0)
ax.set_facecolor('white')
heatmap_with_circles(data_array,row_labels,column_labels, ax=ax)
plt.tight_layout()
plt.show()

但是,现在我需要绘制饼图而不是圆形。并且饼图没有 (row_index,column_index) 参数。

有没有办法在 matplotlib 热图的每个单元格中绘制饼图?

更新heatmap_with_circles中的 for 循环如下:

for row_index, row in enumerate(row_labels,0):
    for column_index, column in enumerate(column_labels,0):
        wedges, _ = plt.pie([20, 10, 5])
        radius = 0.45
        [w.set_center((column_index,row_index)) for w in wedges]
        [w.set_radius(radius) for w in wedges]

结果是

在此处输入图像描述

标签: matplotlibheatmappie-chart

解决方案


您可以访问单独创建的每个楔形plt.pie,然后使用set_radiusset_position重新调整不同的楔形。

wedges, _ = plt.pie([1,2,3])
x_position, y_position = 0, 0
radius = 0.2
[w.set_center((x_position,y_position)) for w in wedges]
[w.set_radius(radius) for w in wedges]

编辑:在您的代码中,在 for 循环中

    for row_index, row in enumerate(row_labels):
        for column_index, column in enumerate(column_labels):
            wedges, _ = plt.pie([1,2,3])
            [w.set_center((row_index,column_index)) for w in wedges]
            [w.set_radius(0.4) for w in wedges]

推荐阅读