使用Seaborn的FacetGrid时如何向所有绘图添加比较线

时间:2019-01-27 16:00:16

标签: python matplotlib seaborn facet-grid

我正在尝试使用FacetGrid将相同的比较线添加到多个绘图中。这是我卡住的地方:

# Import the dataset
tips = sns.load_dataset("tips")

# Plot using FaceGrid, separated by smoke
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")
x = np.arange(0, 50, .5)
y = 0.2*x
plt.plot(y, x, C='k')
plt.show()

Here are the results

如您所见,该线显示在最后一个图上,而不是第一个上。我如何在两者上都得到它?

2 个答案:

答案 0 :(得分:2)

您可以mapFacetGrid拥有相同的功能。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Import the dataset
tips = sns.load_dataset("tips")

# Plot using FaceGrid, separated by smoke
g = sns.FacetGrid(tips, col="smoker", height=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")

def const_line(*args, **kwargs):
    x = np.arange(0, 50, .5)
    y = 0.2*x
    plt.plot(y, x, C='k')

g.map(const_line)

plt.show()

答案 1 :(得分:2)

另一种间接方式是从axes获取FacetGrid对象,然后将线绘制到每个对象上

g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")

axes = g.fig.axes
x = np.arange(0, 50, .5)
y = 0.2*x
for ax in axes:
    ax.plot(y, x, C='k')
plt.show()

enter image description here