在NaN之后,matplotlib无法继续运行 [英] matplotlib not continuing lines after NaN's

查看:52
本文介绍了在NaN之后,matplotlib无法继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组切片:

array([1.0, 2.0, 3.0, None, 4.0, None, 5.0, None, 6.0, None], dtype=object)

在绘制时看起来像

如何使虚线/连接线在无值之后继续?我尝试使用 astype 将数据类型从对象更改为浮点数,并且 None 被替换为 nan 但这没有区别,我还尝试了使用 np.where(np.isnan()) 等的掩码数组但它没有有区别.我的绘图命令非常简单:

How do I get the dotted/connecting lines to continue after the None values? I tried changing the data type from objects to floats using astype and the None's are replaced with nan's but it made no difference, I also tried a masked array using np.where(np.isnan()) etc. but it didn't make a difference. My plotting command is very simply:

plt.plot(x, array, 'ro--')

其中x是一个numpy数组.

where x is a numpy array.

推荐答案

这是正确的行为, mpl 尝试连接相邻点.如果您的点的两边都带有 nan ,则没有有效的方法将它们连接到任何东西.

This is the correct behavior, mpl tries to connect adjacent points. If you have points with a nan on either side, there is no valid way to connect them to anything.

如果您想在绘制时忽略 nan ,则将其去除

If you want to just ignore your nans when plotting, then strip them out

ind = ~np.isnan(np.asarray(data.astype(float)))
plt.plot(np.asarray(x)[ind], np.asarray(data)[ind], 'ro--')

所有的 asarray 只是为了确保示例可以工作,与 astype

All the asarray are just to be sure the example will work, same with the astype

此外,使用阴影(在 Python 解析和语义方面)类(如数组)或通用函数的变量名也是非常糟糕的做法.

also, it is really bad practice to use variable names that shadow (both in terms of python resolution and in terms of semantic) classes (like array) or common functions.

这篇关于在NaN之后,matplotlib无法继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆