multi columns legend in Matlab plots

조회 수: 146 (최근 30일)
Morteza Khosrotabar
Morteza Khosrotabar 2021년 6월 25일
답변: Hari 2024년 9월 3일
Hello everyone
How can I have my legend in two columns with specific numbers in each columns?
for example I have 7 different datas in one plot and I want to have my legend in two columns so that there are 4 datas in first column and 4 datas in second column.

답변 (1개)

Hari
Hari 2024년 9월 3일
Hi Morteza,
I understand that you want to create a legend in a MATLAB plot that is displayed in two columns, with the first column containing four items and the second column containing three items.
You can use the "legend" function to create a legend with multiple columns. Set the "NumColumns" property to 2 to split the legend into two columns. This creates a legend with first column and second column containing 4 and 3 columns respectively.
Here is the sample code that demonstrates the same:
% Example data
x = 1:10;
y1 = rand(1, 10);
y2 = rand(1, 10);
y3 = rand(1, 10);
y4 = rand(1, 10);
y5 = rand(1, 10);
y6 = rand(1, 10);
y7 = rand(1, 10);
% Plot data
figure; % Create a new figure
plot(x, y1, '-o', 'DisplayName', 'Data 1'); hold on;
plot(x, y2, '-s', 'DisplayName', 'Data 2');
plot(x, y3, '-^', 'DisplayName', 'Data 3');
plot(x, y4, '-d', 'DisplayName', 'Data 4');
plot(x, y5, '-x', 'DisplayName', 'Data 5');
plot(x, y6, '-+', 'DisplayName', 'Data 6');
plot(x, y7, '-*', 'DisplayName', 'Data 7');
hold off;
% Create a two-column legend
lgd = legend('NumColumns', 2);
% Add title and labels
title('Example Plot with Multi-Column Legend');
xlabel('X-axis');
ylabel('Y-axis');
% Display grid
grid on;
Output with legend having 2 columns:
Refer to the documentation of "legend" for customizing legends: https://www.mathworks.com/help/matlab/ref/legend.html
I hope this helps!

카테고리

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