如何在Matplotlib中打印一个列表,该列表的元素为"无"或包含方括号的元素(列表中的列表)



我有一个列表,如下所示:

a = [None, None, None, None, None, [0.0016], [0.0015], [0.0014], [0.0014], [0.0013], None, None, None]

问题是,当我想绘制这个列表时,它会返回一个错误:

import matplotlib.pyplot as plt
plt.plot(a)

ValueError:使用序列设置数组元素

我真正想要的是,那些None值被忽略,看起来像空白。

作为一个使用sin函数作为数组的例子,我想要的带有空格的输出如下:示例

您首先需要转换项,这可以使用简短的函数和列表理解来完成。为了确保绘制None值,还需要设置绘制的xlim,以便x轴从0到列表的长度。(您在y轴上隐式绘制值,在x轴上绘制列表索引。(

def transform(item):
if item is None:
return None
else:
return item[0]
a = [transform(item) for item in a]
plt.xlim(0, len(a))
plt.plot(a)

您可以通过以下方式将每个None更改为0:

import matplotlib.pyplot as plt
a = [None, None, None, None, None, [0.0016], [0.0015], [0.0014], [0.0014], [0.0013], None, None, None]
plt.plot([x[0] if not x is None else 0 for x in a])
plt.show()

最新更新