Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error bars in different colors with matplotlib

I have the following code, that produces a simple graph with both vertical and horizontal error bars:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

However, both error bars (vertical and horizontal) are blue, and I don't see how I could specify different colors for both of them. Is this possible? I would like, for example, for all horizontal error bars to be blue and for all vertical error bars to be green.

like image 448
Wild Feather Avatar asked Sep 12 '25 05:09

Wild Feather


2 Answers

Use ecolor keyword:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor='yellow')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

Output:

enter image description here

Different color lines, per bar and per orientation:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor=['yellow','blue'])
elines = el.get_children()
elines[1].set_color('green')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

Output:

enter image description here

like image 73
Scott Boston Avatar answered Sep 13 '25 19:09

Scott Boston


Another "trick" for people with an older matplotlib version:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=0, fmt='b', ecolor='b')
pl.errorbar(x, y, xerr=0, yerr=error_y, fmt='g', ecolor='g')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
like image 34
Wild Feather Avatar answered Sep 13 '25 17:09

Wild Feather