【问题标题】:Transparent error bars without affecting markers不影响标记的透明误差线
【发布时间】:2018-06-21 04:26:56
【问题描述】:

是否可以仅更改误差线的透明度?使用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()

【问题讨论】:

    标签: python-2.7 matplotlib errorbar


    【解决方案1】:

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

    情节线: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()
    

    这给出了:

    更新:在处理多个数据列表时(除了简单地重复上述代码 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()
    

    这个例子给出了:

    【讨论】:

    • 太棒了。但是,如果我单独绘制了大约 30 组数据,我该怎么做呢?我的意思是为了不必做例如条1,条2,...条30。我会尝试附加到bars = []。你有别的想法吗?
    • 这取决于您如何绘制数据,哪种方法是最好的。将有比将所有内容都放入列表更好的方法,但目前很难说。你能更新你的问题吗,最好是MCVE
    • 我已经编辑了我的问题,希望它更清楚。
    • 感谢 MCVE。在您的真实代码中,您是否手动创建了所有数据。即你写x1 = [np.random.uniform(0,10,5)] 30 次了吗?还是您正在使用某种循环?
    • 我将数据保存在一个文件中,并为相同的数据手动创建了多个 (~30) 过滤器。也许我可以用一个循环来绘制它,但它并不是那么简单,因为我使用了不同的颜色、标记等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多