【问题标题】:Is it possible to add the repeated hatches to each bar in seaborn.barplot?是否可以将重复的阴影添加到 seaborn.barplot 中的每个条?
【发布时间】:2021-07-28 16:25:57
【问题描述】:

我想在 seaborn barplot 上添加重复的填充图案。

当然,我检查了下面的问答,但我无法解决我的问题。

Is it possible to add hatches to each individual bar in seaborn.barplot?

在上面的问答中,不同的补丁图案应用于左侧蓝色('-')和右侧蓝色('+')。 我想将相同的补丁图案应用于相同的颜色条; ("//") 应该应用在两个蓝色条上, ("\\") 应该应用在两个绿色条上, ("|") 应该应用在两个红色条上。

我尝试了下面的代码,但我无法实现我的理想身材。

import matplotlib.pyplot as plt
import seaborn as sns

# Set style
sns.set(style="whitegrid", color_codes=True)

# Load some sample data
titanic = sns.load_dataset("titanic")

# Make the barplot
bar = sns.barplot(x="sex", y="survived", hue="class", data=titanic);

hatches = cycle([ "//" , "\\\\" , "|"])

# Loop over the bars
for i,thisbar in enumerate(bar.patches):
    # Set a different hatch for each bar
    thisbar.set_hatch(hatches[i])

plt.show()

【问题讨论】:

    标签: python-3.x seaborn


    【解决方案1】:

    sns.barplot 返回已在其上创建条形图的 matplotlib ax。 (在搜索 seaborn 和 matplotlib 文档以了解如何进行调整时,给返回值一个非常不同的名称可能会造成混淆。)

    ax.patches 确实包含所有条形。首先是一等的所有酒吧,然后是二等的所有酒吧,然后是三等的酒吧。这个分组可以在ax.containers 中找到,它有 3 个容器:每组酒吧一个。遍历这些容器有助于单独孵化每个组。稍后,需要再次创建图例以显示阴影。

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    sns.set(style="whitegrid", color_codes=True)
    titanic = sns.load_dataset("titanic")
    ax = sns.barplot(x="sex", y="survived", hue="class", data=titanic)
    
    hatches = ["//", "\\\\", "|"]
    # Loop over the bars
    for bars, hatch in zip(ax.containers, hatches):
        # Set a different hatch for each group of bars
        for bar in bars:
            bar.set_hatch(hatch)
    # create the legend again to show the new hatching
    ax.legend(title='Class')
    plt.show()
    

    【讨论】:

    • 感谢您的快速回复。但是,我收到错误消息“NameError: name 'handles' is not defined。”使用 matplotlib ver 3.0.3 和 seaborn 0.9.0。
    • 非常感谢您的支持!我确实再现了理想的身材。
    • 感谢您查看代码。 handles 在我的第一次测试中使用,但不是必需的,显然我只是部分删除了它们。新代码应该是正确的。
    猜你喜欢
    • 2016-05-29
    • 2014-10-20
    • 2020-03-27
    • 2017-12-19
    • 2021-07-13
    • 2021-04-22
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多