虚线而不是matplotlib中的缺失值 [英] Dotted lines instead of a missing value in matplotlib

查看:60
本文介绍了虚线而不是matplotlib中的缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据的数组,其中一些值丢失

  y = np.array([np.NAN,45,23,np.NAN,5,14,22,np.NAN,np.NAN,18,23])

当我绘制它时,我缺少这些 NAN(这是预期的)

fig, ax = plt.subplots()轴图(y)plt.show()

我想用一条虚线连接缺失的部分.例如,在缺少3的数据点的情况下,应该有一条虚线连接2和4之间的现有点(对于丢失的数据点7和8也是一样的.如果数据点在间隔的边缘(数据点0)希望有一条水平线将它们连接起来(想象上一个/下一个数据点与可用边相同).

<小时>

要考虑边缘值时的水平线,可以检查它们是否为nan并将其替换为相邻的值.

将 numpy 导入为 np导入matplotlib.pyplot作为plty = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23,np.NAN])x = np.arange(0, len(y))yp = np.copy(y)如果〜np.isfinite(y [0]):yp [0] = yp [1]如果 ~np.isfinite(y[-1]): yp[-1] = yp[-2]掩码 = np.isfinite(yp)无花果,ax = plt.subplots()line, = ax.plot(x[mask],yp[mask], ls="--",lw=1)ax.plot(x,y, color=line.get_color(), lw=1.5)plt.show()

I have an array of some data, where some of the values are missing

y = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23])

When I plot it, I have these NANs missing (which is expected)

fig, ax = plt.subplots()
ax.plot(y)
plt.show()

What I would like to have is a dotted line connecting the missing segments. For example in case of missing datapoint for 3, there should be a dotted line which connects existing points between 2 and 4, (the same for missing datapoints 7 and 8. If the datapoint is on the edge of the interval (datapoint 0) I would like to have a horizontal line connecting them (imagine previous/next datapoint the same as the available edge).


The questions I saw here ask how to remove these empty segments (not what I want). I can solve it by creating another array which will have missing values interpolated and all other values NAN, but it looks to complex to me.

Because this looks like a common case, I hope there is an easier approach.

解决方案

I would say the solution from the linked question can be directly applied here, plotting a dotted line behind the straight line.

import numpy as np
import matplotlib.pyplot as plt

y = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23])
x = np.arange(0, len(y))
mask = np.isfinite(y)

fig, ax = plt.subplots()
line, = ax.plot(x[mask],y[mask], ls="--",lw=1)
ax.plot(x,y, color=line.get_color(), lw=1.5)

plt.show()

To account for the horizontal line in case of the edge values, one may check if they are nan and replace them with the neighboring value.

import numpy as np
import matplotlib.pyplot as plt

y = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23,np.NAN])
x = np.arange(0, len(y))
yp = np.copy(y)
if ~np.isfinite(y[0]): yp[0] = yp[1]
if ~np.isfinite(y[-1]): yp[-1] = yp[-2]

mask = np.isfinite(yp)


fig, ax = plt.subplots()
line, = ax.plot(x[mask],yp[mask], ls="--",lw=1)
ax.plot(x,y, color=line.get_color(), lw=1.5)

plt.show()

这篇关于虚线而不是matplotlib中的缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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