0

I have four subplots (arranged 2x2) and I want to add a line of best fit to these scatter diagrams however there is too much data to manually work it out and input it.

I've looked through similar questions and as they're formatted for one plot I cannot work out how to arrange this for my code.

So far I have...

fig, ax = plt.subplots(2,2, figsize=(20,18))

ax[0,0].scatter(x,y1, color='tab:blue')
ax[0,0].set_xlabel('Title One',fontsize =15)
ax[0,0].set_ylabel('Title Two',fontsize =15)

etc... Finishing with:

plt.show()

My plots have the same x axis with four different y axis labelled y1,y2,y3,y4

1 Answers1

0

The code for best fit line of a scatter plot has already been answered here. And for the other subplots, you can just change the index from ax[0, 0] to other index like ax[0, 1]. Because you are creating a 2x2 subplots, the indices are ax[0,0], ax[0,1], ax[1,0], and ax[1,1].

So implementing for multiple subplots, would be:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.normal(0, 1, 15)
y1 = np.random.normal(0, 1, 15)
y2 = np.random.normal(0, 1, 15)
y3 = np.random.normal(0, 1, 15)
y4 = np.random.normal(0, 1, 15)

fig, ax = plt.subplots(2,2, figsize=(20,18))

ax[0,0].scatter(x, y1, color='tab:blue')
ax[0,0].plot(np.unique(x), np.poly1d(np.polyfit(x, y1, 1))(np.unique(x)))
ax[0,0].set_xlabel('Title One', fontsize=15)
ax[0,0].set_ylabel('Title Two', fontsize=15)

ax[0,1].scatter(x, y2, color='tab:blue')
ax[0,1].plot(np.unique(x), np.poly1d(np.polyfit(x, y2, 1))(np.unique(x)))
ax[0,1].set_xlabel('Title One', fontsize=15)
ax[0,1].set_ylabel('Title Two', fontsize=15)

ax[1,0].scatter(x, y3, color='tab:blue')
ax[1,0].plot(np.unique(x), np.poly1d(np.polyfit(x, y3, 1))(np.unique(x)))
ax[1,0].set_xlabel('Title One', fontsize=15)
ax[1,0].set_ylabel('Title Two', fontsize=15)

ax[1,1].scatter(x, y4, color='tab:blue')
ax[1,1].plot(np.unique(x), np.poly1d(np.polyfit(x, y4, 1))(np.unique(x)))
ax[1,1].set_xlabel('Title One', fontsize=15)
ax[1,1].set_ylabel('Title Two', fontsize=15)

plt.show()

plot

meowulf
  • 367
  • 1
  • 5
  • 14
  • Thank you for your reply, I've just tried running this and I've had the issue: SVD did not converge in Linear Least Squares, do you know how to get around this – Willtswhite May 09 '21 at 11:05
  • maybe you have missing values in your data. try dropping them. – meowulf May 09 '21 at 11:17