How do I make a legend display empty data points?

13 Ansichten (letzte 30 Tage)
Joshua Randle
Joshua Randle am 14 Aug. 2018
Kommentiert: dpb am 14 Aug. 2018
I am trying to display all of these datapoints on a scatter plot the only problem is if they do not have data they are not showing up in the legend what can I do?
if bin1(1,:) ~= [0 0 0];
scatter(bin1(:,1),bin1(:,2),30,[0 0 1],'blue','filled','DisplayName','Below MDC');
end
hold on
if bin2(1,:) ~= [0 0 0];
scatter(bin2(:,1),bin2(:,2),30,[0 0.5 1],'cyan','filled','DisplayName','Below 100 pCi');
end
if bin3(1,:) ~= [0 0 0];
scatter(bin3(:,1),bin3(:,2),30,[0.1 1 0],'green','filled','DisplayName','Below 200 pCi');
end
if bin4(1,:) ~= [0 0 0];
scatter(bin4(:,1),bin4(:,2),30,[1 0.5 0],'yellow','filled','DisplayName','Below 300 pCi');
end
if bin5(1,:) ~= [0 0 0];
scatter(bin5(:,1),bin5(:,2),30,[1 0 0],'red','filled','DisplayName','Below 500 pCi');
end
if bin6(1,:) ~= [0 0 0];
scatter(bin6(:,1),bin6(:,2),30,[1 0 0],'DisplayName','Above 500 pCi','MarkerFaceColor',[0.749019622802734 0 0.749019622802734],'MarkerEdgeColor','none');
end
  2 Kommentare
Rik
Rik am 14 Aug. 2018
You have if statements that prevent plotting under some conditions. You should at the very least remove that if you want the commands to be reached. Also, you see here a prime reason not to use numbered variables: they are a pain to work with and make for messy code.
dpb
dpb am 14 Aug. 2018
To add to Rik's comment, if you execute the plotting routine even if there is no data in the variable (as long as it exists), the linetype/color in the default sequence if not given explicitly or what is assigned if so will show up in the legend.
The problem here is that there is no handle for those that aren't called owing to the conditional and there's no way to force those into a legend object without there being an object to relate to.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adam Danz
Adam Danz am 14 Aug. 2018
Once you do some cleanup following the suggestions made above in the comments under your question, if you still have entirely empty variables that are plotting nothing but you still want to represent those conditions in the legend, plot NaNs.
For example
a = [];
if isempty(a)
a = NaN;
end
p = plot(a, 'b-', 'DisplayName', 'variable A')
legend
  3 Kommentare
Adam Danz
Adam Danz am 14 Aug. 2018
Bearbeitet: Adam Danz am 14 Aug. 2018
Hmmm, when I run that code (R2018a) I only see 'A' in the legend and I get the warning,
Warning: Ignoring extra legend entries.
dpb
dpb am 14 Aug. 2018
Ah! I actually used scatter for the test since that was what OP was using and made the mistake of presuming similar result. Turns out scatter and plot behave differently; another case of inconsistent behavior amongst similar routines.

Melden Sie sich an, um zu kommentieren.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by