How to have two legends on the same plot?

197 ビュー (過去 30 日間)
Miguel Martinez
Miguel Martinez 2023 年 2 月 23 日
コメント済み: Umar 2024 年 8 月 5 日
I just want to see a basic example of how to put two legends on the same plot on MATLAB 2020 and beyond...
  1 件のコメント
Umar
Umar 2024 年 8 月 5 日

Hi @ Miguel Martinez,

To address your query regarding, “ However, when using semilogy it didn't work”

First, generate some sample data for plotting. For this example, we will create two sets of data.

x = 1:10;

y1 = 10 ./ x;

y2 = log(x);

Plot the data using the semilogy function.

semilogy(x, y1, 'b', x, y2, 'r');

Add legends for both datasets using the legend function. To display two legends, you can use the legend function twice.

legend('Data 1', 'Data 2'); legend('Location', 'northwest'); % Adjust the location of the first legend

If you want, you can customize the legends further by specifying the location, font size, font weight, etc. For example:

legend('Data 1', 'Data 2', 'Location', 'northwest', 'FontSize', 10, 'FontWeight', 'bold');

Please see attached plot.

サインインしてコメントする。

回答 (2 件)

Askic V
Askic V 2023 年 2 月 23 日
Perhaps you meant this:
t = 0:0.1:5;
y = sin(t);
z = cos(t);
figure; hold on;
for i = 1:2
p1(i) = plot(t, y,'r');
p2(i) = plot(t, z,'b');
end
hold off
legend([p1(1) p2(1)],'sin', 'cos');
ah1 = axes('position',get(gca,'position'),'visible','off');
legend(ah1, [p1(2) p2(2)], {'Test1','Test2'}, 'Location','SouthWest');
  2 件のコメント
Magalhães, A. L.
Magalhães, A. L. 2024 年 8 月 3 日
It worked fine for me. However, when using semilogy it didn't work. Apparently, this method forces it to be just a plot.
Magalhães, A. L.
Magalhães, A. L. 2024 年 8 月 3 日
編集済み: Magalhães, A. L. 2024 年 8 月 3 日
All you need to fix this is to add the following row after the last semilogy's row:
set(gca,'yscale','log')

サインインしてコメントする。


KSSV
KSSV 2023 年 2 月 23 日
figure
hold on
plot(rand(1,10),'r')
plot(rand(1,10),'b')
legend('One','Two')

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Translated by