Reputation: 17
Hi there Im trying to plot a line of best fit onto the following graph. The line probably won't be linear and i'm not sure how/ what libary to use in order to plot this. Any help would be appreciated! Image of the plot
Code used:
c_filt = [1.16, 2.51, 1.15, 1.52, 1.11, 1.84, 1.07, 3, 2, 1.71, 0.48, 1.85, 1.32, 1.17, 1.48, 2.59, 1.67, 1.91, 1.5]
lat = [-53, -51, -54, -53, -31, -28, -25, -9, -11, -9, -12, -8, -10, -8, -9, -14, 19, 15, 7]
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
%matplotlib inline
plt.scatter(x = c_filt, y = lat, marker = '.', color = 'black', label = 'TSS Network')
plt.ylabel('Latitude')
plt.xlabel('c', style = 'italic')
plt.ylim(-60, 60)
plt.xlim(0, 3.5)
plt.title('LATITUDES EFFECT ON C PARAMETER')
plt.legend(markerfirst = True, frameon = True, loc='upper right')
plt.tight_layout()
plt.savefig('Lat,c.png')
Upvotes: 1
Views: 3810
Reputation: 172
If you sort the x values monotonically then you can use a polynomial fit and chose the order you want (in this case I fitted a second order polynomial).
import numpy as np
import matplotlib.pyplot as plt
c_filt = [1.16, 2.51, 1.15, 1.52, 1.11, 1.84, 1.07, 3, 2, 1.71, 0.48, 1.85, 1.32, 1.17, 1.48, 2.59, 1.67, 1.91, 1.5]
lat = [-53, -51, -54, -53, -31, -28, -25, -9, -11, -9, -12, -8, -10, -8, -9, -14, 19, 15, 7]
#sort values
sort_indexes = sorted(range(len(c_filt)), key=lambda k: c_filt[k])
sorted_c_filt = sorted(c_filt)
sorted_lat = []
for index in sort_indexes:
sorted_lat.append(lat[index])
# fit with polynomial of second orders
coeff = np.polyfit(sorted_c_filt, lat, 2)
x = np.linspace(sorted_c_filt[0], sorted_c_filt[-1], num = 100)
Polynomial = np.polyval(coeff, x)
# plot
plt.figure()
plt.title('LATITUDES EFFECT ON C PARAMETER')
plt.plot(sorted_c_filt, sorted_lat, '.')
plt.plot(x, Polynomial, '-', label = 'Polyfit')
plt.legend(loc='lower right')
plt.xlabel('c')
plt.ylabel('Latitude')
plt.show()
Upvotes: 4