Home > Blockchain >  Creating error bar that extends from data point to an exact curve
Creating error bar that extends from data point to an exact curve

Time:02-18

I have the following plot that I generated with matplotlib. enter image description here

I would like to draw error bars from the data points to the red curve. I have experimented with matplotlib.pyplot.errorbars() function, but I could not find a decent way to do this. Here is the code for the plot:

# imports
import numpy as np
import matplotlib.pyplot as plt

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data
plt.scatter(target_time, results, label='Simulation Result')

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()

CodePudding user response:

You can do this using matplotlib.pyplot.errorbars by specifiying the error. Here the error is given by the distance between the blue point and the red curve. In the code, I've done it for you assuming the error is in the y-direction. This can be similarily done for error in the x-direction.

import numpy as np
import matplotlib.pyplot as plt

# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])

# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2

# plot data

yerr = abs(results -  np.cos(2*target_time)**2) #calcuating the y-error
plt.errorbar(target_time, results,yerr=yerr, marker='o', ls ='none', label='Simulation Result') #This plots both the points AND the error bars. I replaced plt.scatter with this.

# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()

Additonally, you can also add fancy styles e.g., errorbar caps, color, etc. Please refer to the wiki page: enter image description here

  • Related