How To Make Scatter Plot with Regression Line using Seaborn in Python?

How To Make Scatter Plot with Regression Line using Seaborn in Python?

To make a scatter plot with a regression line using Seaborn in Python, you can use the sns.regplot() function. The regplot() function draws a scatter plot of two variables and then fits the regression model and plots the resulting regression line.

Here's a step-by-step guide:

  • Install the necessary libraries:

If you haven't installed Seaborn and its dependencies yet, you can do so using pip:

pip install seaborn 
  • Import the necessary libraries:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt 
  • Generate or provide data:

For demonstration purposes, I'll generate random data:

# Generating random data np.random.seed(42) x = np.random.rand(100) y = 1.5 * x + np.random.normal(0, 0.15, 100) 
  • Create a scatter plot with a regression line:
sns.set_style("whitegrid") plt.figure(figsize=(8, 6)) sns.regplot(x=x, y=y, scatter_kws={'s': 50}, line_kws={'color': 'red'}, ci=None) plt.title('Scatter Plot with Regression Line') plt.xlabel('X Values') plt.ylabel('Y Values') plt.show() 

In the sns.regplot() function:

  • scatter_kws allows customization of the scatter points.
  • line_kws allows customization of the regression line.
  • ci is the confidence interval for the regression estimate. Setting it to None disables the shading around the regression line.
  • Display the plot:

The plt.show() call displays the plot.

The output will be a scatter plot with a regression line. The regression line will give you a visual representation of the linear relationship between the x and y variables.


More Tags

threadpool android-mediaplayer html-email rdbms oracle-xe react-native-navigation-v2 spring-boot android-multidex cube-script dynamically-generated

More Programming Guides

Other Guides

More Programming Examples