Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent error bars without affecting markers

Is it possible to change the transparency of just the error bars? When using plt.errorbar() changing alpha affects both the markers and the error bars.

EDIT:

In my case, I have several different sets of data, and each value has its own error, so I plot each data set using plt.errorbar(). Here is a MWE using 3 different data sets:

import matplotlib.pyplot as plt
import numpy as np

x1 = [np.random.uniform(0,10,5)]
x2 = [np.random.uniform(0,10,5)]
x3 = [np.random.uniform(0,10,5)]
y1 = [np.random.uniform(0,10,5)]
y2 = [np.random.uniform(0,10,5)]
y3 = [np.random.uniform(0,10,5)]
err1 = [np.random.uniform(1,2, 5)]
err2 = [np.random.uniform(1,2, 5)]
err3 = [np.random.uniform(1,2, 5)]

plt.errorbar(x1, y1, xerr=err1, yerr=err1, fmt='ro', ms=10)
plt.errorbar(x2, y2, xerr=err2, yerr=err2, fmt='bs', ms=10)
plt.errorbar(x3, y3, xerr=err3, yerr=err3, fmt='g^', ms=10)
plt.show()
like image 739
EternalGenin Avatar asked Jan 11 '18 18:01

EternalGenin


1 Answers

This can be done by examining what is returned when calling plt.errorbar(). Looking at the documentation it returns a

plotline : Line2D instance

x, y plot markers and/or line

caplines : list of Line2D instances

error bar cap

barlinecols : list of LineCollection

horizontal and vertical error ranges

Each of these can be modified used set_alpha(). So, to avoid changing the transparency of the markers, don't change plotline.

A full example:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)

# example variable error bar values
yerr = 0.1 + 0.2*np.sqrt(x)
xerr = 0.1 + yerr

fig, ax = plt.subplots()
markers, caps, bars = ax.errorbar(x, y, yerr=yerr, xerr=xerr,
            fmt='o', ecolor='black',capsize=2, capthick=2)

# loop through bars and caps and set the alpha value
[bar.set_alpha(0.5) for bar in bars]
[cap.set_alpha(0.5) for cap in caps]

plt.show()

Which gives:

enter image description here

Update: A possible solution when dealing with multiple lists of data (apart from simply repeating the above code x amount of time) would be to put things (such as x values, y values etc.) in another list, then loop through these, meaning you don't have to manually code this. Using your edited example:

# Put all your data into other lists
x_list = [x1, x2, x3]
y_list = [y1, y2, y3]
err_list = [err1, err2, err3]
formats = ['ro', 'bs', 'g^']

# Loop through data and plot
for x, y, err, f in zip(x_list, y_list, err_list, formats):
    markers, caps, bars = plt.errorbar(x, y, xerr=err, yerr=err, fmt=f, ms=10)
    [bar.set_alpha(0.5) for bar in bars]
    [cap.set_alpha(0.5) for cap in caps]

plt.show()

Which for the example gives:

enter image description here

like image 130
DavidG Avatar answered Nov 04 '22 20:11

DavidG