我的数据集包含有关决策支持模型的短期和长期影响的信息。我想将其绘制在具有4条的条形图中:
下面是一些示例代码:
df = pd.DataFrame(columns=["model", "time", "value"])
df["model"] = ["on"]*2 + ["off"]*2
df["time"] = ["short", "long"] * 2
df["value"] = [1, 10, 2, 4]
sns.barplot(data=df, x="model", hue="time", y="value")
plt.show()
它看起来像这样:
还有许多其他相关图形,它们已经建立了颜色约定。型号开/关以颜色的色调编码。长期与短期以颜色饱和度编码。因此,假设我给变量赋予了颜色值。如何为条形图中的每个单独的条分配单独的颜色?
seaborn.barplot的docs仅显示color
,它为所有元素指定一种颜色,而palette
仅显示不同的色相值,不同的颜色。
答案 0 :(得分:1)
现有答案显示了如何使用pyplot安排条形图的好方法。
不幸的是,我的代码严重依赖于其他seaborn功能,例如错误栏等。因此,我希望能够保留seaborn barplot功能并仅指定自己的颜色。
有可能在matplotlib补丁程序中迭代seaborn barplot中的条。这样就可以设置颜色,阴影等: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()
答案 1 :(得分:0)