Search code examples
matlabmatlab-figure

Datetick take into account NaN in plot


I have a series y that contains values, some of which are NaN some numeric (double).

The series has an associated vector d which contains the datenum dates.

Example:

y=[NaN(5,1); rand(10,1)]
d=now-14:now

When I run:

plot(d,y)

I get the graph I want; the NaN observations are taken out.

However, when I run:

plot(d,y); datetick

then my graph starts from the beginning and takes into account all the observations (even when y is a NaN).

How can I prevent this from happening?


Solution

  • From the documentation we can see that there is an easy way (shown below) to preserve the current axes limits.

    plot(d,y);
    datetick('keeplimits');
    

    The 'keeplimits' argument does exactly what it suggests, maintaining the x-axis limits whilst converting the tick values to dates. You may also want to pass 'keepticks' to preserve tick mark locations.


    The behaviour you describe seems contrary to the docs:

    datetick selects a label format based on the minimum and maximum limits of the specified axis.

    From this statement I would expect the values to remain the same, but there is obviously something about the way the limits are handled internally which means the NaN points are included. At least we are given a simple work around!