Customizing Histogram legend to show "Edge Color" instead of "Bar Color".

49 views (last 30 days)
Hello. I was trying to plot two histograms in the same figure, customizing them to have no Fill color and have different Edge colors. What I'm trying to do is to make the outline and not the fill to be the indicator of the plot. Hence, I was expecting the legend to do the same, since I am not aware of any command to mention it specifically. However, what I found is that the legend only recognizes the fill color as the indicator, not the line (example shown below).
Can anyone help by suggesting a method to customize the legend such that it display the line colors instead of the body colors as indicators? Thank you!
Example: (Please note that I didn't use my original code, which is cumbersome, rather I picked up an example code from another answer, just to make you understand what the specific issue is)
data1=randi(10,[1,100]);
data2=randi(10,[1,100]);
histogram(data1,'FaceColor','none', 'EdgeColor', 'r');
hold on;
histogram(data2,'FaceColor', 'none', 'EdgeColor', 'b');
legend('Data1','Data2')
The output I get is this (as you can see, the legend on top-right shows blank for colors, since I set FaceColor to 'none' for both):
Any help would be appreciated. Thanks!

Answers (1)

Image Analyst
Image Analyst on 2 May 2022
Maybe use text instead of legend
yl = ylim;
xl = xlim;
yt = yl(1) + 0.9 * (yl(2)-yl(1));
xt = xl(1) + 0.85 * (xl(2)-xl(1));
text(xt, yt, '---Data1', 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 12);
yt = yl(1) + 0.85 * (yl(2)-yl(1));
text(xt, yt, '---Data2', 'Color', 'b', 'FontWeight', 'bold', 'FontSize', 12);
  2 Comments
Shourya Mukherjee
Shourya Mukherjee on 4 May 2022
That's one possibility yes. But I'm looking for a method to tweak the legend options. Any idea if one exists?
Image Analyst
Image Analyst on 7 May 2022
You can just get the handle to the legend when you create it then call delete(), then create the new strings, and call text again
yl = ylim;
xl = xlim;
yt1 = yl(1) + 0.9 * (yl(2)-yl(1));
xt = xl(1) + 0.85 * (xl(2)-xl(1));
t1 = text(xt, yt1, '---Data1', 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 12);
yt2 = yl(1) + 0.85 * (yl(2)-yl(1));
t2 = text(xt, yt2, '---Data2', 'Color', 'b', 'FontWeight', 'bold', 'FontSize', 12);
% Get rid of old text.
delete(t1)
delete(t2)
% Tweak captions and re-display text as legend.
t1 = text(xt, yt1, '---New Data1', 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 12);
t2 = text(xt, yt2, '---New Data2', 'Color', 'b', 'FontWeight', 'bold', 'FontSize', 12);

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!