1

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

这是我的代码。

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'

我该怎么办?

4

2 回答 2

2

您只需要使用 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')
于 2016-01-06T07:44:48.230 回答
0

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

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

在此处输入图像描述

于 2016-01-06T09:51:25.653 回答