How to force a plot to show trailing NaNs
8 views (last 30 days)
Show older comments
I have a simple set of values that I display on a bar plot or a line plot. Sometimes, depending on the outcome of steps in the code, some values will be set to NaN.
When they appear in the middle of the data series (ex: [1 2 3 NaN 8 9]), the plot shows 6 "data points", with the 4th not being plotted. However, there is a corresponding x-axis location for this missing NaN point.
However, when the NaN appears at the end of the data series (ex: [1 2 3 6 8 NaN]), the plot will onl show 5 "data points", with the 6th not only non being plotted, but completely missing a corresponding x-axis location. This creates problems, as I need the x-axis to be consistent, and will subsitute the x-axis locations with custom xtick labels that should show all the possible x-axis values. Also, I would like to subsitute a text box to appear where there is missing/NaN data, to add a note about why this is missing. Obviously all of this is not possible if the location for the data point is removed and the series is simply truncated.
Any pointers are appreciated. Thanks.
0 Comments
Answers (1)
Image Analyst
on 23 Sep 2021
Try this:
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 25;
fprintf('Beginning to run %s.m ...\n', mfilename)
v = [1 2 nan 3 6 8 5.5 1.5 NaN]
bar(v, 1);
grid on;
xlim([1, length(v)+1]);
yl = ylim;
nanIndexes = find(isnan(v))
for k = 1 : length(v)
if isnan(v(k))
y = 0;
str = 'NaN';
else
y = v(k)
str = sprintf('%.1f', y);
end
text(k, y, str, ...
'Color', 'b', 'FontSize', 25, ...
'FontWeight', 'bold', ...
'VerticalAlignment', 'bottom', ...
'HorizontalAlignment', 'center');
end
g = gcf;
g.WindowState = 'maximized'
fprintf('Done running %s.m.\n', mfilename)
4 Comments
Image Analyst
on 27 Sep 2021
So just don't create str and call text if the number is a valid number. Attach your data if you need more help.
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!