【问题标题】:Create a waffle chart with hatches in python using pywaffle使用 pywaffle 在 python 中创建带有阴影的华夫饼图
【发布时间】:2021-03-02 09:59:32
【问题描述】:

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

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}    
)

由于灰色的形状很难区分,我想画出最后一个类别(在图和图例中),但我不知道如何在颜色中添加阴影。我有一个具有相同类别的条形图,我在其中添加了阴影,所以我想保持一致。

【问题讨论】:

    标签: python matplotlib plot waffle-chart


    【解决方案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()
    

    【讨论】:

    • 谢谢@JohanC!我不知道patheffects。这解决了我的问题。数据隐藏在数据框中。我本可以更明确一点,对此感到抱歉。
    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多