Dotted lines instead of a missing value in matplotlib

2024/11/16 12:00:03

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()

enter image description here

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.

Answer

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 plty = 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()

enter image description here

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 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)
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()

enter image description here

https://en.xdnf.cn/q/71347.html

Related Q&A

How to change the creation date of file using python on a mac?

I need to update the creation time of a .mp4 file so that it will appear at the top of a list of media files sorted by creation date. I am able to easily update both the accessed and modified date of …

Classification tree in sklearn giving inconsistent answers

I am using a classification tree from sklearn and when I have the the model train twice using the same data, and predict with the same test data, I am getting different results. I tried reproducing on…

Modifying binary file with Python

i am trying to patch a hex file. i have two patch files (hex) named "patch 1" and "patch 2"the file to be patched is a 16 MB file named "file.bin".i have tried many differ…

python error : module object has no attribute AF_UNIX

this is my python code :if __name__ == __main__: import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect((0.0.0.0, 4000)) import time time.sleep(2) #sock.send(1)print …

How to speed up pandas string function?

I am using the pandas vectorized str.split() method to extract the first element returned from a split on "~". I also have also tried using df.apply() with a lambda and str.split() to produc…

sqlalchemy autoloaded orm persistence

We are using sqlalchemys autoload feature to do column mapping to prevent hardcoding in our code.class users(Base):__tablename__ = users__table_args__ = {autoload: True,mysql_engine: InnoDB,mysql_chars…

Data Normalization with tensorflow tf-transform

Im doing a neural network prediction with my own datasets using Tensorflow. The first I did was a model that works with a small dataset in my computer. After this, I changed the code a little bit in or…

Relationship of metaclasss __call__ and instances __init__?

Say Ive got a metaclass and a class using it:class Meta(type):def __call__(cls, *args):print "Meta: __call__ with", argsclass ProductClass(object):__metaclass__ = Metadef __init__(self, *args…

How to present numpy array into pygame surface?

Im writing a code that part of it is reading an image source and displaying it on the screen for the user to interact with. I also need the sharpened image data. I use the following to read the data an…

Following backreferences of unknown kinds in NDB

Im in the process of writing my first RESTful web service atop GAE and the Python 2.7 runtime; Ive started out using Guidos shiny new ndb API.However, Im unsure how to solve a particular case without t…