ax = sns.barplot(x="size", y="algorithm", hue="ordering", data=df2, palette=sns.color_palette("cubehelix", 4))
在创建 seaborn barplot 之后(或之前),有没有办法让我为每个条传递影线(填充图案和颜色)值?
在 seaborn
或 matplotlib
中执行此操作的方法会有很大帮助!
最佳答案
您可以遍历通过捕获 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()
感谢@kxirog 在评论中提供此附加信息:
for i,thisbar in enumerate(bar.patches)
将一次从左到右遍历每种颜色,因此它将遍历左边的蓝色条,然后是右边的蓝色条,然后是左边的绿色条等。
关于python - 是否可以在 seaborn.barplot 中为每个单独的条形图添加影线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467188/