Customizing Histogram legend to show "Edge Color" instead of "Bar Color".
조회 수: 8 (최근 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!
