在缺少数据的线图中添加误差线

Adding error bars in line figure with missing data

我想按照建议在缺失数据之间画线 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: unsupported operand type(s) for -: 'NoneType' and 'NoneType'

我该怎么办?

您只需要使用 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')

感谢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 是做什么的,即使在阅读了定义页面之后...