5

如何将网格线(垂直和水平)添加到seaborncatplot?我发现可以在箱线图上做到这一点,但我有多个方面,因此需要一个猫图。与其他答案相反, catplot 不允许ax争论。

这段代码是从这里借来的。

import seaborn as sns
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
plt.show()

有任何想法吗?谢谢!

编辑:提供的答案是有效的,但对于多面图,只有最后一个图继承了网格。

import seaborn as sns
sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
plt.grid()
plt.show()

有人可以向我解释为什么以及如何解决它吗?

4

2 回答 2

11

您可以通过两种方式在 seaborn 图上设置网格:

1.plt.grid()方法:

你需要使用grid里面的方法matplotlib.pyplot。你可以这样做:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
plt.grid()  #just add this
plt.show()

这导致了这个图表: 在此处输入图像描述

2.sns.set_style()方法

您还可以使用sns.set_stylewhich 将在任何给定的所有子图中启用网格FacetGrid。你可以这样做:

import seaborn as sns
import matplotlib.pyplot as plt


sns.set(style="ticks")
exercise = sns.load_dataset("exercise")
sns.set_style("darkgrid")
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
plt.show()

返回此图: 在此处输入图像描述

于 2020-04-29T14:34:45.107 回答
6

来到这个问题,寻找一种将网格添加到 FacetGrid 图的方法,而不使用“whitegrid”样式。在尝试了许多解决方案后,我发现在多面图中必须将 {'axes.grid' : True} 添加到 set_style 函数中:

import seaborn as sns
sns.set_style("ticks",{'axes.grid' : True})
g = sns.FacetGrid(df, col="column_variable",col_wrap=4, height=2.3)
于 2021-06-17T20:04:43.523 回答