现有答案显示了如何使用 pyplot 排列条形图的好方法。
不幸的是,我的代码严重依赖于其他 seaborn 功能,例如误差线等。所以我希望能够保留 seaborn barplot 功能并只指定我自己的颜色。
可以将 seaborn 条形图中的条形作为 matplotlib 补丁进行迭代。这允许设置颜色、阴影等:Is it possible to add hatches to each individual bar in seaborn.barplot?
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
df = pd.DataFrame(columns=["model", "time", "value"])
df["model"] = ["on"]*2 + ["off"]*2
df["time"] = ["short", "long"] * 2
df["value"] = [1, 10, 2, 4]
fig, ax = plt.subplots()
bar = sns.barplot(data=df, x="model", hue="time", y="value", edgecolor="white")
colors = ["red", "green", "blue", "black"]
# Loop over the bars
for i,thisbar in enumerate(bar.patches):
# Set a different hatch for each bar
thisbar.set_color(colors[i])
thisbar.set_edgecolor("white")
但是,如果您这样做,它不会更新图例。您可以使用以下代码创建自定义图例。这很复杂,因为我需要为每个图例条目提供多个色块。这显然很复杂:Python Matplotlib Multi-color Legend Entry
# add custom legend
ax.get_legend().remove()
legend_pos = np.array([1, 10])
patch_size = np.array([0.05, 0.3])
patch_offset = np.array([0.06, 0])
r2 = mpatches.Rectangle(legend_pos, *patch_size, fill=True, color='red')
r3 = mpatches.Rectangle(legend_pos + patch_offset, *patch_size, fill=True, color='blue')
ax.add_patch(r2)
ax.add_patch(r3)
ax.annotate('Foo', legend_pos + 3* patch_offset - [0, 0.1], fontsize='x-large')
plt.show()