Reputation: 2061
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?
Upvotes: 1
Views: 380
Reputation: 2061
Thanks to Paul's answer, this is the revised code.
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()
AlthoughI am still not sure what isfinite does, even after reading the definition page...
Upvotes: 0
Reputation: 68186
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')
Upvotes: 2