owl
owl

Reputation: 1961

Matplotlib: Getting different colors in data lines with error bars

I am trying to draw two data lines with error bars, each having the same color as the data line. However, I get another thin line with a color I have not specified in each data line when I add an error bar.

Also, I would like to make the caps of the error bars thicker but the option capthick is not valid here.

Could anybody please help me fix these issues?

This is my code.

import matplotlib.pyplot as plt
from pylab import *
import numpy as np

xaxis = [1, 2, 3]
mean1 = [1,2,3.6]
se1 = [0.2, 0.5, 0.9]
mean2 = [10, 29, 14]
se2 = [3, 4, 2]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('X', fontsize = 16)
ax.set_ylabel('Y', fontsize = 16)

ax.axis([0, 5, 0, 35])
ax.plot(xaxis, mean1, 'r--', linewidth = 4)
ax.errorbar(xaxis, mean1, yerr = se1, ecolor = 'r', elinewidth = 2, capsize = 5)
ax.plot(xaxis, mean2, 'b--', linewidth = 4)
ax.errorbar(xaxis, mean2, yerr = se2, ecolor = 'b', elinewidth = 2, capsize = 5)
plt.show()

Upvotes: 1

Views: 13652

Answers (1)

will
will

Reputation: 10650

The extra thin line is coming from the errorbar() call.

errorbar will draw a line too, what you're doing is changing the colour of the error bars, but not the actual lines (hence it using the standard matplotlib first two colours, blue and green.

it's all in the documentaion, here.

To achieve what you want, you only need to use the errorbar() function;

This does what you want i think, maybe jsut tweak the numbers a bit.

import matplotlib.pyplot as plt
from pylab import *
import numpy as np

xaxis = [1, 2, 3]
mean1 = [1,2,3.6]
se1 = [0.2, 0.5, 0.9]
mean2 = [10, 29, 14]
se2 = [3, 4, 2]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('X', fontsize = 16)
ax.set_ylabel('Y', fontsize = 16)

ax.axis([0, 5, 0, 35])
linestyle = {"linestyle":"--", "linewidth":4, "markeredgewidth":5, "elinewidth":5, "capsize":10}
ax.errorbar(xaxis, mean1, yerr = se1, color="r", **linestyle)
ax.errorbar(xaxis, mean2, yerr = se2, color="b", **linestyle)
plt.show()

I put the common line style arguments into a dict which gets unpacked.

enter image description here

Upvotes: 4

Related Questions