我想按照建议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'
我该怎么办?
答案 0 :(得分: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')
答案 1 :(得分:0)
感谢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()
虽然即使在阅读了定义页面后,我仍然不确定是什么意思...