How to change change color of line or patch in legend
48 次查看(过去 30 天)
显示 更早的评论
I have two different data that I'm plotted down with both data have patch on it. I used the code below but when I run with both patch on, the legend didn't follow the colors assigned on the plot
figure(1)
figure('units', 'normalized', 'outerposition', [0 0 0.30 0.25])
hold on
patch([f_final fliplr(f_final)], [Arousal1_PSD_lo fliplr(Arousal1_PSD_hi)], 'k', 'EdgeColor', 'none', 'FaceAlpha','0.5')
plot(f_final, Arousal1_PSD_mean, 'k','linewidth', 2)
patch([f_final fliplr(f_final)], [Arousal2_PSD_lo fliplr(Arousal2_PSD_hi)], 'b', 'EdgeColor', 'none', 'FaceAlpha','0.5')
plot(f_final,Arousal2_PSD_mean, 'b','linewidth', 2)
hold off
xlabel('Frequency')
xlim ([0 30])
xticks (0:5:30)
ylabel('(PSD (uV^2/Hz))')
title('Sox14GFP/GFP vs Sox14GFP/+ Arousal 1 PSD Estimate')
set(gca, 'FontSize', 8, 'TickDir', 'out', 'box', 'off')
legend({'Sox14GFP/GFP';'Sox14GFP/+'})
this is how the graph look like:
0 个评论
回答(2 个)
Image Analyst
2022-7-29
You need to get the handles from whatever you want to be in the legend, like the returned value of plot() or patch() or whatever. Then pass only those handles into legend().
2 个评论
Voss
2022-7-29
Note that changing the order of the plot vs patch code changes the order that those things are created, which changes their order in the plot (i.e., which lines and patches appear on top of or below which other lines and patches), which may or may not be another problem you'd now need to solve.
Voss
2022-7-29
The problem: the first patch is used as a legend entry:
figure()
hold on
patch()
plot([0 1])
patch()
plot([1 0])
hold off
legend({'line 1','line 2'})
One solution: pass only the line handles to legend:
figure()
hold on
patch()
h1 = plot([0 1]); % the output from plot is a line handle
patch()
h2 = plot([1 0]);
hold off
legend([h1 h2],{'line 1','line 2'}) % use the line handles in legend
Another solution: set the patches' HandleVisibility to 'off' so that only the lines show up in the legend:
figure()
hold on
patch('HandleVisibility','off')
plot([0 1])
patch('HandleVisibility','off')
plot([1 0])
hold off
legend({'line 1','line 2'})
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!