Multiple Lines in errorbar Matplotlib

Question:

The problem occurs when having a set of X values and Y values (41 to be exact) and I want an error bar, this works, but it creates a lot of lines instead only one.
Here is my code:

y_values = [
    np.mean(image_data['some_parameter'][x]) 
    for x in image_data['some_parameter']
]

yerr = [
    statistics.stdev(image_data['some_parameter'][x]) 
    for x in image_data['some_parameter']
]


x_values = list(image_data['some_parameter'].keys())

plt.errorbar(x_values, y_values, yerr=yerr, capsize=5, ecolor="red")
plt.show()

In the end, the result looks something like this:

the plot that comes out

Asked By: ziad_dp

||

Answers:

The problem is due to x_values being unsorted. You can fix it with something like

sorted_indices = np.argsort(x_values)
new_x_values = np.array(x_values)[sorted_indices]
new_y_values = np.array(y_values)[sorted_indices]
new_yerr = np.array(yerr)[sorted_indices]

plt.errorbar(new_x_values, new_y_values, yerr=new_yerr, capsize=5, ecolor="red",
             linestyle="-", marker="")

You can also disable the lines interconnecting the data points by setting linestyle="" and add markers by setting marker="o" for instance. See here for info on markers and here for the linestyle documentation.

Answered By: johnc