在facetgrid的每个子图中绘制回归线

时间:2017-10-31 01:47:11

标签: python pandas seaborn

def global_regression(x, y, **kwargs):
    # Plot
    import matplotlib.pyplot as plt
    ax = plt.scatter(x.values, y.values)

    # Draw 'red' regression line
    x_plot = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100)
    m, b = np.polyfit(x.values, y.values, 1)
    plt.plot(x_plot, m * x_plot + b, color='red', alpha=0.5)

   # Draw diagonal 1:1 line
   ax.plot(ax.get_xlim(), ax.get_ylim(), ls='--', c='.3', alpha=0.5)

   # Create nice-looking grid for ease of visualization
   ax.grid(which='major', alpha=0.5)
   ax.grid(which='minor', alpha=0.15)

import seaborn as sns
import matplotlib.pyplot as plt
g = sns.FacetGrid(df, col='val')
g.map(global_regression, 'actual', 'predicted')
g.add_legend()
g.set(alpha=0.25)

在上面的代码中,我想创建一个facetgris并使用global_regression函数绘制回归线。但是,我收到此错误: *** AttributeError: 'PathCollection' object has no attribute 'get_xlim' ax.get_alim()[0]。如何解决这个问题?我不想使用regplot

1 个答案:

答案 0 :(得分:1)

plt.scatter返回PathCollection。尽管你调用它ax这不是一个轴,因此不能这样对待它,即它没有get_xlim属性。因此错误。

而是随意调用散点图并通过plt.gca()获取轴。

foo = plt.scatter(x.values, y.values)
ax = plt.gca()

请注意,您可能会使用上面的代码遇到新的错误,但是需要有一个Minimal, Complete, and Verifiable example

相关问题