透明误差条,不影响标记

时间:2018-01-11 18:41:34

标签: python-2.7 matplotlib errorbar

是否可以更改错误栏的透明度?使用plt.errorbar()时,更改alpha会影响标记和误差线。

修改

就我而言,我有几组不同的数据,每个值都有自己的错误,因此我使用plt.errorbar()绘制每个数据集。这是一个使用3种不同数据集的MWE:

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()

1 个答案:

答案 0 :(得分:3)

这可以通过检查调用plt.errorbar()时返回的内容来完成。查看documentation,它会返回

  

plotline:Line2D实例

     

x,y绘制标记和/或行

     

caplines:Line2D实例列表

     

错误栏上限

     

barlinecols:LineCollection列表

     

水平和垂直误差范围

每个都可以使用set_alpha()进行修改。因此,为避免更改标记的透明度,请勿更改plotline

一个完整的例子:

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()

给出了:

enter image description here

更新:处理多个数据列表时的一个可能的解决方案(除了简单地重复上面的代码x时间量之外)就是放置东西(例如x值,y值等)。 )在另一个列表中,然后遍历这些,这意味着您不必手动编码。使用您编辑过的示例:

# 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()

示例中给出了:

enter image description here