As part of my research project, I was working on performing linear regression with some data using matplotlib. Unfortunately, I am unable to get my line to touch the origin; matplotlib seems to cut it off at the minimum value of my dataset. How can I fix this and get my line to touch the origin? As reference, here is my code:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from statsmodels import api as sm
def file_analysis(csv_file, state):
"""
This method takes in a file object and the name of a state.
:param csv_file: Pass in a csv file object.
:param state: Name of the state as a string.
:return: None.
"""
data = pd.read_csv(csv_file)
data = data[["Total Cases", "Total Deaths"]]
y = data["Total Deaths"]
x = data["Total Cases"]
results = sm.OLS(y, x).fit()
plt.scatter(x, y)
yhat = results.params[0] * x
print(results.params)
plt.ylim(ymin=0)
plt.xlim(xmin=0)
plt.margins(0)
fig = plt.plot(x, yhat, lw=4, c="orange", label="regressionline")
plt.xlabel("Total Cases", fontsize=20)
plt.ylabel('Total Deaths', fontsize=20)
plt.title(state)
plt.savefig(state + "_scatterplot" + ".png")
plt.show()
with open(state + "_analysis.txt", "w") as file:
file.write(results.summary().as_text())
And here is the resulting scatter-plot after passing in the name of the state and the csv file for the state: