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) 将从左到右迭代每种颜色,因此它将遍历左蓝色条,然后是右蓝色条,然后是左侧绿色条等.