×

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it.

Linear regression

One of the simplest and most widely used Machine Learning techniques is linear regression. It is a statistical technique for performing predictive analysis. This algorithm works on the assumption it takes based on the types of both variables and takes a linear relationship. We can calculate the model's necessary coefficients to make decisions based on the unseen data. This process can be done only if a relationship exists between the variables.

Plotting data is nothing but visualizing the given data into a graph. It is always better to plot pictorial data to comprehend it in a better way. Before applying multiple regressions, we have to check if there are any relationships between all features. We will use the pairplot() method from the seaborn package to plot the relationship between all the features. This pairplot() will produce a histogram along with a scatter plot mixing all the features.

To plot these regressions, we will need multiple python libraries like NumPy, Pandas, sklearn, matplotlib, etc.

You can use the below code to import all these libraries:

# Importing the required methods and modules for plotting 
  
# all required libraries   
import pandas as pd  
import warnings  
 import numpy as np  


# For data visualizing   
import seaborn as sns  
import matplotlib.pyplot as plt  
from mpl_toolkits.mplot3d import Axes3D  
%matplotlib inline 


 
# For building the required model  
from sklearn import linear_model  
  

Of this, we imported all the libraries required.

We use this dataset for further codes:7420         4        2

 costareabedroomfloor
012300000742532
115250000896843
213250000999934
315215000754053
413410000743042

By looking at the below code, we will get the histogram and scatter plot

# Visualizing the relationships between features using pair plots  
sns.pairplot(data = housing, height = 3) 

Output:

How to plot multiple linear regression in Python

Here we used the pairplot() function, and we can also see that the first row of this graph is a linear relationship between the price and area features of the dataset. We can see the scatter plot of the rest of all variables is random, and there is no relationship between them. We should always select only one multiple independent features having a relation.

Building a Multiple Linear Regression Model:

To build a regression model, we can use every feature where there will be no relationship with collinearity among the elements, we can use all features to build a model. In this code, we will use LinearRegression() function from sklearn.

Example

# Building a Multiple Linear Regression Model  
  
# Set the independent and dependent features of the data set 
X = housing.iloc[:, 1:].values  
y = housing.iloc[:, 0].values  
  
  
# Initializing the model class from the sklearn package and fitting our data into it  
reg = linear_model.LinearRegression()  
reg.fit(X, y)  
  
# Printing  intercept and the coefficients of the regression equation  
print('Intercepts: ', reg.intercept_)  
print('Coefficient array: ', reg.coef_)  

Output:

How to plot multiple linear regression in Python

We can also convert this model into a 3-dimensional graph. To convert that, we use the below code where all the data points will be in grey color dots in the chart, and the blue plane represents the linear model.

Example

# Preparing the required data  
independent = housing[['area', 'bedroom']].values.reshape(-1,4)  
dependent = housing['cost']  
  
# Creating a variable for every dimension  
a = independent[:, 0]  
b = independent[:, 1]  
c = dependent  
  
a_range = np.linspace(5, 10, 35)    
b_range = np.linspace(3, 6, 35)   
a1_range = np.linspace(3, 6, 35)  
a_range, a_range, a1_range = np.meshgrid(a_range, b_range, a1_range)  
viz = np.array([a_range.flatten(), b_range.flatten(), a1_range.flatten()]).T  
  
# predicting price values by using the linear regression model built above  
predictions = reg.predict(viz)  
  
# Evaluating the model by using the R2 square of the model  
r2 = reg.score(A, B)  
  
# Ploting the model for visualization  
plt.style.use('fivethirtyeight')  
  
# Initializing a matplotlib figure  
fig = plt.figure(figsize = (15, 6))  
  
axis1 = fig.add_subplot(131, projection = '3d')  
axis2 = fig.add_subplot(132, projection = '3d')  
axis3 = fig.add_subplot(133, projection = '3d')  
  
axis = [axis1, axis2, axis3]  
  
for ax in axis:  
    ax.plot(a, b, c, color='k', zorder = 10, linestyle = 'none', marker = 'o', alpha = 0.1)  
    ax.scatter(a_range.flatten(), b_range.flatten(), predictions, facecolor = (0,0,0,0), s = 20, edgecolor = '#70b3f0')  
    ax.set_alabel('Area', fontsize = 10, labelpad = 10)  
    ax.set_blabel('Bedrooms', fontsize = 10, labelpad = 10)  
    ax.set_clabel('Prices', fontsize = 10, labelpad = 10)  
    ax.locator_params(nbins = 3, axis = 'a')  
    ax.locator_params(nbins = 3, axis = 'a')  
  
axis1.view_init(elev=25, azim=-60)  
axis2.view_init(elev=15, azim=15)  
axis3.view_init(elev=25, azim=60)  
  
fig.suptitle(f'Multi-Linear Regression Model Visualization (R2 = {r2}, ("fontsize"))

Output:

How to plot multiple linear regression in Python

Conclusion:

In this way, we plot multiple linear regression models in Python.


Related Topics

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.