pythonmatplotlibseabornfacet-gridrelplot

Overlay a line function on a scatter plot


My challenge is to overlay a custom line function graph over a scatter plot I already have, the code looks like follows:

base_beta = results.params
X_plot = np.linspace(0,1,400)

g = sns.FacetGrid(data, size = 6)
g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")

Where base_beta is only a constant, and then one coefficient. Basically, I want to overlay a function that plots a line y = constant + coefficient * x

I tried to overlay a line using this but it did not work.

g = g.map_dataframe(plt.plot, X_plot, X_plot*base_beta[1]+base_beta[0], 'r-')
plt.show()

The current scatter plot looks like so:
enter image description here

Can any one help me with this?

--ATTEMPT 1

base_beta = results.params
X_plot = np.linspace(0,1,400)
Y_plot = base_beta [0] + base_beta[1]*X_plot

g = sns.FacetGrid(data, size = 6)
g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")
plt.plot(X_plot, Y_plot, color='r')
plt.show()

Resulted in the same graph but no line: enter image description here


Solution

  • You can just call plt.plot to plot a line over the data.

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    
    data = pd.DataFrame()
    data['usable_area'] = 5*np.random.random(200)
    data['price'] =  10*data['usable_area']+10*np.random.random(200)
    
    X_plot = np.linspace(0, 7, 100)
    Y_plot = 10*X_plot+5
    
    g = sns.FacetGrid(data, height = 6)
    g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")
    plt.plot(X_plot, Y_plot, color='r')
    plt.show()
    

    Produces:

    enter image description here