Python、Seaborn FacetGrid 更改标题

Python, Seaborn FacetGrid change titles

我正在尝试在 Seaborn 中创建 FacetGrid

我的代码目前是:

g = sns.FacetGrid(df_reduced, col="ActualExternal", margin_titles=True)
bins = np.linspace(0, 100, 20)
g.map(plt.hist, "ActualDepth", color="steelblue", bins=bins, width=4.5)

这是我的图

现在,我想要标题 "Internal" 和 "External"

,而不是 "ActualExternal =0.0" 和 "ActualExternal =1.0"

而且,我希望 xlabel 显示 "Percentage Depth"

而不是 "ActualDepth"

最后,我想添加一个"Number of Defects"的ylabel。

我试过谷歌搜索并尝试了一些方法,但到目前为止没有成功。你能帮帮我吗?

谢谢

您可以通过 g.axes 访问 FacetGrid (g = sns.FacetGrid(...)) 的轴。有了它,您可以自由使用任何您喜欢的 matplotlib 方法来调整绘图。

更改标题

axes = g.axes.flatten()
axes[0].set_title("Internal")
axes[1].set_title("External")

更改标签:

axes = g.axes.flatten()
axes[0].set_ylabel("Number of Defects")
for ax in axes:
    ax.set_xlabel("Percentage Depth")

请注意,我更喜欢 FacetGrid 的内部 g.set_axis_labelsset_titles 方法之上的方法,因为它使要标记的轴更加明显。

虽然您可以遍历轴并使用 matplotlib 命令单独设置标题,但使用 seaborn 的 built-in 工具来控制标题会更简洁。例如:

# Add a column of appropriate labels
df_reduced['measure'] = df_reduced['ActualExternal'].replace({0: 'Internal',
                                                              1: 'External'}

g = sns.FacetGrid(df_reduced, col="measure", margin_titles=True)
g.map(plt.hist, "ActualDepth", color="steelblue", bins=bins, width=4.5)

# Adjust title and axis labels directly
g.set_titles("{col_name}")  # use this argument literally
g.set_axis_labels(x_var="Percentage Depth", y_var="Number of Defects")

这样做的好处是无论您有 1D 还是 2D 小平面都不需要修改。

设置多个标题的最简单方法是:

titles = ['Internal','External']

for ax,title in zip(g.axes.flatten(),titles):
    ax.set_title(title )