【问题标题】:Adding error bars in line figure with missing data在缺少数据的线图中添加误差线
【发布时间】:2016-01-06 07:20:04
【问题描述】:

我想按照here 的建议在缺失数据之间画线,但带有误差线。

这是我的代码。

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5]
y_value = [12, None, 18, None, 20]
y_error = [1, None, 3, None, 2]

fig = plt.figure()
ax = fig.add_subplot(111)
plt.axis([0, 6, 0, 25])
ax.plot(x, y_value, linestyle = '-', color = 'b', marker = 'o')
ax.errorbar(x, y_value, yerr = y_error, linestyle = '' , color = 'b')
plt.show()

但由于缺少数据,我得到了

TypeError: 不支持的操作数类型 -: 'NoneType' 和 'NoneType'

我该怎么办?

【问题讨论】:

    标签: python matplotlib errorbar


    【解决方案1】:

    您只需要使用 numpy(您已导入)来掩盖缺失值:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = [1, 2, 3, 4, 5]
    y_value = np.ma.masked_object([12, None, 18, None, 20], None)
    y_error = np.ma.masked_object([1, None, 3, None, 2], None)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlim([0, 6])
    ax.set_ylim([0, 25])
    ax.plot(x, y_value, linestyle = '-', color = 'b', marker = 'o')
    ax.errorbar(x, y_value, yerr = y_error, linestyle = '' , color = 'b')
    

    【讨论】:

    • 感谢您的帮助和this page,我能够创建一个我想要的图,我会发布供您参考。
    【解决方案2】:

    感谢 Paul 的回答,这是修改后的代码。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.array([1, 2, 3, 4, 5])
    y_value = np.ma.masked_object([12, None, 18, None, 20], None).astype(np.double)
    y_error = np.ma.masked_object([1, None, 3, None, 2], None).astype(np.double)
    
    masked_v = np.isfinite(y_value)
    masked_e = np.isfinite(y_error)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.axis([0, 6, 0, 25])
    ax.plot(x[masked_v], y_value[masked_v], linestyle = '-', color = 'b', marker = 'o')
    ax.errorbar(x[masked_e], y_value[masked_e], yerr = y_error[masked_e], linestyle = '' , color = 'b')
    plt.show()
    

    虽然我仍然不确定 isfinite 是做什么的,即使在阅读了定义页面之后...

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2014-12-02
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多