Customizing Histogram legend to show "Edge Color" instead of "Bar Color".
29 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
Image Analyst
2022-5-2
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 个评论
Image Analyst
2022-5-7
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);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!