Certainly! Below is a self-contained example of using matplotlib.pyplot.errorbar to plot data points with error bars. This example includes both vertical and horizontal error bars.
python
import matplotlib.pyplot as plt
import numpy as np
# Generate some example data
x = np.linspace(0, 10, 11) # x values from 0 to 10 in steps of 1
y = np.sin(x) # y values as sine of x
# Generate random errors for x and y
x_err = np.random.uniform(0.1, 0.3, size=len(x)) # Random x errors between 0.1 and 0.3
y_err = np.random.uniform(0.1, 0.3, size=len(y)) # Random y errors between 0.1 and 0.3
# Create the plot with error bars
plt.errorbar(
x, y,
xerr=x_err, # Horizontal error bars
yerr=y_err, # Vertical error bars
fmt='o', # Format of the data points (circle markers)
ecolor='red', # Color of the error bars
capsize=5, # Size of the caps on the error bars
capthick=2, # Thickness of the caps
elinewidth=1, # Thickness of the error bars
label='Data with errors'
)
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example of errorbar in Matplotlib')
plt.legend()
plt.grid(True)
# Show the plot
plt.show()
Explanation:
Data Generation:
x is an array of values from 0 to 10.
y is the sine of x.
x_err and y_err are random errors for x and y.
plt.errorbar Parameters:
x and y: The data points.
xerr and yerr: The errors in the x and y directions.
fmt: The format string for the data points (e.g., 'o' for circles).
ecolor: Color of the error bars.
capsize: Size of the caps at the ends of the error bars.
capthick: Thickness of the caps.
elinewidth: Thickness of the error bars.
Plot Customization:
Labels, title, legend, and grid are added for clarity.
When you run this code, it will display a plot with data points and error bars in both the x and y directions. The error bars will have red caps and lines.