1

I have a bunch of scattered data that I would like to plot and add a best fit line (y=ax+b) and represent the equation with the associated error (maybe R), and showing 95 % confidence level curves. Moreover, each point (x,y) has a name that should appear in the legend preferably each point should have different shape. Could anyone please help me out with this?

x=np.array([100,65,20,85])
xerr=np.array([5,3,2,5])
y=np.array([1,0.75,1.25,2])
yerr=np.array([0.1,0.03,0.01,0])
Pygin
  • 907
  • 6
  • 12

2 Answers2

1

Answering my question I know this much of the code but I want to add the 95% confidence boundaries as well as the error associated with trend line equation in the same graph!

x=np.array([100,65,20,85])
xerr=np.array([5,3,2,5])
y=np.array([1,0.75,1.25,2])
yerr=np.array([0.1,0.03,0.01,0])


fig, ax = plt.subplots()


ax.errorbar(x, y,
            xerr=xerr,
            yerr=yerr,
            fmt='o')


ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('Test Code')


z = np.polyfit(x.flatten(), y.flatten(), 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")
plt.title("y=%.6fx+%.6f"%(z[0],z[1])) 

plt.show()
Pygin
  • 907
  • 6
  • 12
0

I'm not sure what exactly you want to do. Maybe, something like this? About the 95% confidence level curves, you can take a look here How to plot confidence interval in Python?.

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    fig = plt.figure()
    x = np.array([100,65,20,85])
    y = np.array([1,0.75,1.25,2])
    Error_x = np.array([5,3,2,5])
    Error_y = np.array([0.1,0.03,0.01,0])

    labels = ['A', 'B', 'C', 'D']
    symbols = ['v', '^', '<', '>']

    for i in range(0, len(x)):
        plt.scatter(x[i], y[i], marker=symbols[i], s=70)
        plt.errorbar(x[i], y[i], xerr=Error_x[i], c='black')
        plt.errorbar(x[i], y[i], yerr=Error_y[i], c='black')

    z = np.polyfit(x.flatten(), y.flatten(), 1)
    p = np.poly1d(z)
    plt.plot(x,p(x),"r--")

    ci = 0.95 * np.std(y)/np.mean(y)
    ax.fill_between(sorted(x), p(x)-ci, p(x)+ci, color='b', alpha=.4)

    for l in range(0, len(labels)):
        plt.text(x[l], y[l] + 0.03, labels[l])

    plt.grid()
    plt.tight_layout()
    plt.savefig("test.png")
    plt.show()

enter image description here

heiLou
  • 209
  • 1
  • 3
  • 11
  • That is what I almost want to do, but the equation of the line as well as the error of the best fit should be also shown. – Pygin May 29 '20 at 00:53