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:

回答(2 个)

Image Analyst
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 个评论
Jedidiah Maatita
Jedidiah Maatita 2022-7-29
I tried just now trying to change it and found that I just need to change the positioning of the patch code and the plot to fix the legend.
I moved all the plot code upwards and then patch codes underneath and it fixed the legend colors
Voss
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
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'})

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by