# Simple Linear Regression in Python – Step 5.) Visualize the Result of Simple Linear Regression

To visualize the data in python, we are going to use the library of matplotlib, which we have already imported in step1.

We are going to first plot the training set data and then we are going to plot the predicted result.

#Import Libraries

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#Import data
x = dataset.iloc[:,:-1].values
y =dataset.iloc[:,1].values

#Splitting training set and testing set
from sklearn.cross_validation import train_test_split
xtrain, xtest, ytrain, ytest =train_test_split(x,y,test_size=0.25)

#Training and Fitting model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(xtrain, ytrain)

#Predicting using the Model

y_prediction = regressor.predict(xtest)

#Visualising the Training set Results
plt.scatter(xtrain, ytrain,color=’red’)
plt.plot(xtrain,regressor.predict(xtrain), color=’blue’)
plt.title(‘Bank Account Balance vs Years of Work (Training set)’)
plt.xlabel(‘ Years of Work’)
plt.ylabel(‘Bank Account Balance’)
plt.show

#Visualise Predicted result
plt.scatter(xtest, y_prediction,color=’red’)
plt.plot(xtrain,regressor.predict(xtrain), color=’blue’)
plt.title(‘Bank Account Balance vs Years of Work (Predicted Result)’)
plt.xlabel(‘Years of Work’)
plt.ylabel(‘Bank Account Balance’)
plt.show

Scatter plot is used to illustrate the regression model. It is quite easy to use the “matplotlib”.

• plt.scatter(xtrain, ytrain,color=’red’), we define the x variable and y variable, and then we declare the color for the data point.
• plt.plot(xtrain,regressor.predict(xtrain), color=’blue’) we plot the line in color blue, which shows the regression line. xtrain is our x variable data, and regressor.predict(ytrain) is the predicted value from our previous section.
• plt.title(‘Bank Account Balance vs Years of Work (Training set)’) ; this sets the title of the graph.
• plt.xlabel(‘ Years of Work’); this labels the x axis.
• plt.ylabel(‘Bank Account Balance’); this labels the y axis.
• At the end, enter plt.show; and this will display the scatter plot for you.

##### Other Sections on Linear Regression :

Step 5.) Visualize the Result of Simple Linear Regression