【问题标题】:Is it possible to add hatches to each individual bar in seaborn.barplot?是否可以在 seaborn.barplot 中为每个单独的条添加阴影?
【发布时间】:2016-05-29 18:37:47
【问题描述】:
ax = sns.barplot(x="size", y="algorithm", hue="ordering", data=df2, palette=sns.color_palette("cubehelix", 4))

在创建 seaborn 条形图之后(或之前),我有没有办法为每个条形传递孵化(填充图案和颜色)值? 在seabornmatplotlib 中执行此操作的方法会很有帮助!

【问题讨论】:

  • 我不确定您所说的“每个单独的酒吧”是什么意思。您的意思是您希望每个条形都有阴影线,还是希望不同的条形有不同的阴影线?
  • @mwaskom 感谢您的回复!我需要不同的酒吧有不同的孵化。您可以通过在 sns.barplot 中传递 hatch='//' 将所有条形设置为具有相同的阴影。不知道如何在不同的酒吧里有不同的孵化..

标签: python matplotlib visualization bar-chart seaborn


【解决方案1】:

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

这是一个最小的示例,它是来自here 的条形图示例的修改版本。

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

感谢 cmets 中的@kxirog 提供此附加信息:

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

【讨论】:

  • 非常感谢,这正是我想要的!您认为还有一种方法可以将影线添加到图例中吗?
  • 正如每个人都知道的那样,因为我花了一点时间才弄清楚:for i,thisbar in enumerate(bar.patches): 从左到右一次迭代每种颜色,所以它会迭代左边的蓝色条,然后是右边的蓝色条,然后是左边的绿色条等等......
  • @kxirog 只需将ax.legend() 放在添加阴影之后和plt.show() 之前。
  • 对于box = sns.boxplot 使用box.artists 而不是.patches
  • 对于hist = sns.histplot 使用hist.collections 而不是.patches(至少对于element='step'
猜你喜欢
  • 2021-07-28
  • 2014-10-20
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多