是否可以在seaborn.barplot中为每个单独的栏添加阴影?

kxi*_*rog 6 python visualization matplotlib bar-chart seaborn

ax = sns.barplot(x="size", y="algorithm", hue="ordering", data=df2, palette=sns.color_palette("cubehelix", 4))
Run Code Online (Sandbox Code Playgroud)

在创建一个seaborn barplot之后(或之前),有没有办法让我传入每个栏的舱口(填充图案和颜色)值?一种方法可以做到这一点,seaborn或者matplotlib会有很多帮助!

tmd*_*son 14

你可以通过捕获AxesSubplot返回的barplot循环遍历创建的条形,然后循环遍历它patches.然后,您可以使用设置每个单独栏的阴影.set_hatch()

这里有一个小例子,这是从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);

# Define some hatches
hatches = ['-', '+', 'x', '\\', '*', 'o']

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

感谢@kxirog对此附加信息的评论:

for i,thisbar in enumerate(bar.patches) 将从左到右迭代每种颜色,因此它将遍历左蓝色条,然后是右蓝色条,然后是左侧绿色条等.

  • 正如每个人都知道的那样,因为它花了我一点时间来弄清楚:`对于i,这个列在枚举(bar.patches)中:`从左到右迭代每个颜色,所以它会遍历左边的蓝色条,然后是右边的蓝色条,然后是左边的绿色条等... (4认同)
  • 非常感谢,这正是我一直在寻找的!您认为有没有办法将舱口添加到图例中? (3认同)
  • @kxirog 只需在添加影线之后和 `plt.show()` 之前放置 `ax.legend()`。 (2认同)
  • 对于“hist = sns.histplot”,使用“hist.collections”而不是“.patches”(至少对于“element='step'”) (2认同)