Search code examples
pythonmatplotliberrorbar

Adding error bars in line figure with missing data


I want to draw lines between missing data as suggested here but with error bars.

This is my code.

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

But because of the missing data, I get

TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'

What should I do?


Solution

  • You just need to use numpy (which you've imported) to mask the missing values:

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