For my project I have six sets of data to put on a scatter plot, like so:
plot(ax, ay, '.r', bx, by, '.b', cx, cy, '.m', dx, dy, '.c', ex, ey, '.y', fx, fy, '.k');
Sometimes these sets of data will be empty, so bx
and by
might have nothing in them, therefore getting skipped over.
Is there any way to build a legend that will match the right label to the right color piece of data? In other words, data in the [cx, cy]
would always match the label 'c'
on the legend next to a magenta dot, even when there is no 'b'
. My current legend is as follows:
legend('a', 'b', 'c', 'd', 'e', 'f', -1);
Thanks!
You can get the results you want if you first replace any sets containing empty data with NaN
values. For example:
x = [];
y = [];
if isempty(x) || isempty(y)
x = nan;
y = nan;
end
plot(1:10, rand(1,10), 'r', x, y, 'g', 1:10, rand(1,10), 'b');
legend('r', 'g', 'b');
Leaving x
and y
as empty would give a warning when creating the legend and result in an incorrect legend. When passing empty vectors ([]
) to the plot
command, it simply doesn't create a line object for that data. When passing a NaN
value, it creates but doesn't render a line object, so it still exists and can have a legend entry generated for it.