使用 pywaffle 在 python 中创建带有阴影的华夫饼图

时间:2021-03-02 09:59:32

标签: python matplotlib plot waffle-chart

我想为以下数据框创建一个灰色形状的华夫饼图

data = pd.DataFrame({'Category': ['a', 'b', 'c', 'd'], 'no_occurrence' : [594, 5, 10, 9]})

这是我到目前为止所做的基于 this post

import matplotlib.pyplot as plt 
from pywaffle import Waffle
fig = plt.figure(
    FigureClass=Waffle, 
    rows=5,
    colors = ('lightgrey', 'black', 'darkgrey', 'lightgrey'),
    values=list(data['no_occurrence']/4),
    labels=list(data['Category']),
    icons = 'sticky-note', 
    icon_size = 11,
    figsize=(12, 8),
    icon_legend = True,
    legend={'loc': 'lower left','bbox_to_anchor': (0, -0.4), 'ncol': len(data), 'fontsize': 8}    
)

由于灰色形状很难区分,我想对最后一个类别(在图中和图例中)进行阴影处理,但我不知道如何在颜色中添加阴影部分。我有一个具有相同类别的条形图,我在其中添加了影线,因此我希望保持一致。

1 个答案:

答案 0 :(得分:1)

当使用图标作为华夫饼图中的元素时,它们在内部表示为具有特殊字体的文本对象。

使用 patheffects,可以将阴影添加到图中的图标和图例中。

由于您没有提供玩具数据,也没有提供图片,我编了一些数据来展示这些想法。由于我的图例图标比图中的图标小,我为图例使用了更密集的阴影线。

import matplotlib.pyplot as plt
from matplotlib import patheffects
import numpy as np
from pywaffle import Waffle

values = [5, 14, 17, 18]
fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    colors=('lightgrey', 'black', 'darkgrey', 'lightgrey'),
    values=values,
    labels=[*'abcd'],
    icons='sticky-note',
    icon_size=60,
    figsize=(12, 8),
    icon_legend=True,
    legend={'loc': 'lower left', 'bbox_to_anchor': (0, -0.4), 'ncol': 4, 'fontsize': 15,
            'facecolor': 'white', 'edgecolor': 'black'})
for t in fig.ax.texts[-values[-1]:]:
    t.set_path_effects([patheffects.PathPatchEffect(hatch='xxx', fc='lightgrey', ec='white')])  # color='lightgrey')])
fig.ax.legend_.legendHandles[-1].set_path_effects(
    [patheffects.PathPatchEffect(hatch='xxxxx', fc='lightgrey', ec='white')])
fig.tight_layout()
plt.show()

example waffle chart