I have a function that adds a legend I want to make the legend grou... (2024)

41 views (last 30 days)

Show older comments

A Poyser on 25 Jun 2024 at 10:31

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t

  • Link

    Direct link to this question

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t

Commented: Mathieu NOE on 26 Jun 2024 at 14:31

Accepted Answer: dpb

  • Sample1.csv
  • Sample2.csv
  • Sample3.csv
  • Sample4.csv
  • Sample5.csv
  • Sample6.csv
  • Sample7.csv

Open in MATLAB Online

I have managed to make a code that automates the plotting of data but I would like the code to group the plots into disticnt groups.

Let us say samples 1,3,5 - is group 1

and 2,4,6- is group 2

7,9,11 group 3

8,10,12 is group 4

and finally 13 & 14 is group 5

this is the code

Nsamples = 7;

%

L = 100; % coupon gauge section (mm)

A = 17; % coupon cross-sectional area (mm^2)

%

figure(1);

hold;

figure(2);

hold

%

for k = 1:Nsamples

%

file_name = ['Sample' num2str(k) '.csv'];

%

T = readtable(file_name,'VariableNamingRule','preserve');

%

[test(k).disp,test(k).force,test(k).eyy] = post_fun(T);

%

figure(1)

h(k) = plot(test(k).disp,test(k).force);

set(h(k),'LineWidth',2);

%

figure(2)

g(k) = plot(test(k).eyy*100,1000*test(k).force/A);

set(g(k),'LineWidth',2);

%

leg_string{k} = ['Sample ' num2str(k)];

%

end

%

figure(1)

set(gcf,'Position',[200 200 1024 768],'Color',[1 1 1]);

set(gca,'FontSize',24);

xlabel('Displacement (mm)','FontSize',32,'Interpreter','latex');

ylabel('Force (kN)','FontSize',32,'Interpreter','latex');

box on

grid on

legend(leg_string,'FontSize',28,'Interpreter','latex');

%

%

figure(2)

set(gcf,'Position',[200 200 1024 768],'Color',[1 1 1]);

set(gca,'FontSize',24);

xlabel('Strain (\%)','FontSize',32,'Interpreter','latex');

ylabel('Stress (MPa)','FontSize',32,'Interpreter','latex');

box on

grid on

legend(leg_string,'FontSize',28,'Interpreter','latex');

%

%

function [disp,force,eyy] = post_fun(T)

%

disp = table2array(T(:,4));

force = table2array(T(:,end));

eyy = table2array(T(:,10));

%

index = isnan(disp) | isnan(force) | isnan(eyy) | disp < 0 | force < 0 | eyy < 0;

%

disp(index) = [];

force(index) = [];

eyy(index) = [];

%

[~,index] = max(force);

disp(index+1:end) = [];

eyy(index+1:end) = [];

%

end

I have added sample 1-7 . csv but the code doesn't seem to run on this page.

this is what the figure1+2 looks like

I have a function that adds a legend I want to make the legend grou... (2)

I have a function that adds a legend I want to make the legend grou... (3)

Hopefully you can help.

Thanks

Alex

1 Comment

Show -1 older commentsHide -1 older comments

Mathieu NOE on 25 Jun 2024 at 13:57

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3195356

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3195356

hello

you could probably use this Fex submission to get to this result

GridLegend - File Exchange - MATLAB Central (mathworks.com)

so each group of 3 data could have same color and just different linestyle / markerstyle

other interesting legend tweaks are available on the same Fex (search "legend")

Sign in to comment.

Sign in to answer this question.

Accepted Answer

dpb on 25 Jun 2024 at 15:14

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#answer_1476786

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#answer_1476786

Edited: dpb on 25 Jun 2024 at 17:46

Open in MATLAB Online

  • Sample1.csv
  • Sample2.csv
  • Sample3.csv
  • Sample4.csv
  • Sample5.csv
  • Sample6.csv
  • Sample7.csv

Nsamples = 7;

G=ones(1,2*Nsamples);

G(1:2:5)=1;

G(2:2:6)=2;

G(7:2:11)=3;

G(8:2:12)=4;

G(13:14)=5;

M={'x','+','*','s','d'}; % a morker for each group

C={'r','b','k','m','g'}; % and a color

L = 100; % coupon gauge section (mm)

A = 17; % coupon cross-sectional area (mm^2)

figure(1);

hold on

figure(2);

hold on

for k = 1:Nsamples

file_name = ['Sample' num2str(k) '.csv'];

T = readtable(file_name,'VariableNamingRule','preserve');

[test(k).disp,test(k).force,test(k).eyy] = post_fun(T);

ig=G(k); % get group id for kth file

figure(1)

h(k) = plot(test(k).disp,test(k).force,'LineWidth',2,'Marker',M(ig),'Color',C{ig});

figure(2)

g(k) = plot(test(k).eyy*100,1000*test(k).force/A,'LineWidth',2,'Marker',M(ig),'Color',C{ig});

leg_string{k} = ['Group ' num2str(ig)];

end

%

figure(1)

set(gcf,'Position',[200 200 1024 768],'Color',[1 1 1]);

set(gca,'FontSize',24);

xlabel('Displacement (mm)','FontSize',32,'Interpreter','latex');

ylabel('Force (kN)','FontSize',32,'Interpreter','latex');

box on

grid on

legend(h([1 2 7]),leg_string([1 2 7]),'FontSize',28,'Interpreter','latex','location','northwest');

I have a function that adds a legend I want to make the legend grou... (6)

figure(2)

set(gcf,'Position',[200 200 1024 768],'Color',[1 1 1]);

set(gca,'FontSize',24);

xlabel('Strain (\%)','FontSize',32,'Interpreter','latex');

ylabel('Stress (MPa)','FontSize',32,'Interpreter','latex');

grid on

legend(g([1 2 7]),leg_string([1 2 7]),'FontSize',28,'Interpreter','latex','location','northwest');

I have a function that adds a legend I want to make the legend grou... (7)

function [displ,force,eyy] = post_fun(T)

displ=T{:,4};

force=T{:,end};

eyy =T{:,10};

ix=all(isfinite([displ force eyy]),2) & all([displ force eyy]>0,2);

displ=displ(ix);

force=force(ix);

eyy=eyy(ix);

[~,imax] = max(force);

displ(imax+1:end) = [];

force(imax+1:end) = [];

eyy(imax+1:end) = [];

end

The legends to display are those for the first element in each group so the linestyle, marker and color will match the legend string.

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

More Answers (1)

Mathieu NOE on 25 Jun 2024 at 15:23

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#answer_1476801

  • Link

    Direct link to this answer

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#answer_1476801

Open in MATLAB Online

this is a simple solution, where the files are processed in the order that you wished (cf list = [1 3 5 2 4 6 7 9 11 8 10 12 13 14]) , then visually afterwards we force the line color an style to follow a given order so the group is easily identified (appears also in the legend if that helps too)

here the result for figure 1 :

I have a function that adds a legend I want to make the legend grou... (9)

% Nsamples = 7;

%

L = 100; % coupon gauge section (mm)

A = 17; % coupon cross-sectional area (mm^2)

%

%

% pos array

posA = [200 200 1024 768];

f1 = figure('Position',posA,'Color',[1 1 1]); hold on

a1 = gca;

f2 = figure('Position',posA,'Color',[1 1 1]); hold on

a2 = gca;

% line style / colors

colors = [

0 0 1

1 0 0

0 0.75 0

0.5 0 0.5

1 0.5 0

];

styles = {'-','--','-.'};

inds = 0; % index for style indexing

spacing = size(styles,2); % period for style indexing

indc = 1; % index for color indexing

% Let us say samples 1,3,5 - is group 1

% and 2,4,6- is group 2

% 7,9,11 group 3

% 8,10,12 is group 4

% and finally 13 & 14 is group 5

% create a list of groups of 3 data files according to description above :

% list = [1 3 5 2 4 6 7 9 11 8 10 12 13 14]

list = [1 3 5 2 4 6 7 ] % here we have only 7 files

for ck = 1:numel(list)

k = list(ck);

% colors and linestyle index management

inds = inds +1;

if inds >spacing

inds = inds - spacing;

indc = indc +1;

end

%

file_name = ['Sample' num2str(k) '.csv'];

%

T = readtable(file_name,'VariableNamingRule','preserve');

%

[disp,force,eyy] = post_fun(T);

%

h = plot(a1,disp,force,'LineWidth',2,"color",colors(indc,:),"linestyle",styles{inds});

set(a1,'FontSize',24);

xlabel(a1,'Displacement (mm)','FontSize',32,'Interpreter','latex');

ylabel(a1,'Force (kN)','FontSize',32,'Interpreter','latex');

box on; grid on

%

g = plot(a2,eyy*100,1000*force/A,'LineWidth',2,"color",colors(indc,:),"linestyle",styles{inds});

set(a2,'FontSize',24);

xlabel(a2,'Strain (\%)','FontSize',32,'Interpreter','latex');

ylabel(a2,'Stress (MPa)','FontSize',32,'Interpreter','latex');

box on; grid on

%

leg_string{ck,1} = ['Group ' num2str(indc) ' / Sample ' num2str(k)];

%

end

%

legend(a1,leg_string,'FontSize',13,'Interpreter','latex');

legend(a2,leg_string,'FontSize',13,'Interpreter','latex');

%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%ùù

function [disp,force,eyy] = post_fun(T)

%

% disp = table2array(T(:,4));

% force = table2array(T(:,end));

% eyy = table2array(T(:,10));

d = table2array(T); % one single call to table2array is enough

disp = d(:,4);

force = d(:,end);

eyy = d(:,10);

%

index = isnan(disp) | isnan(force) | isnan(eyy) | disp < 0 | force < 0 | eyy < 0;

%

disp(index) = [];

force(index) = [];

eyy(index) = [];

%

[~,index] = max(force);

disp(index+1:end) = [];

force(index+1:end) = [];

eyy(index+1:end) = [];

%

end

2 Comments

Show NoneHide None

A Poyser on 26 Jun 2024 at 14:21

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3196396

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3196396

Thanks, I accepted the other answer just because it was the first that I read. But I have tried this one and it seems to work well too

Mathieu NOE on 26 Jun 2024 at 14:31

Direct link to this comment

https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3196406

  • Link

    Direct link to this comment

    https://matlabcentral.mathworks.com/matlabcentral/answers/2131771-i-have-a-function-that-adds-a-legend-i-want-to-make-the-legend-group-certain-plots-together-yet-so-t#comment_3196406

ok - no problem .

fyi, you can also vote for other answers that you find useful - that rewards people who spent time on your problem

Sign in to comment.

Sign in to answer this question.

See Also

Categories

MATLABGraphicsFormatting and AnnotationLabels and AnnotationsLegend

Find more on Legend in Help Center and File Exchange

Tags

  • plot
  • figure
  • legend

Products

  • MATLAB

Release

R2022b

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


I have a function that adds a legend I want to make the legend grou... (12)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

I have a function that adds a legend I want to make the legend grou... (2024)

FAQs

What is the function of legend in MATLAB? ›

legend creates a legend with descriptive labels for each plotted data series. For the labels, the legend uses the text from the DisplayName properties of the data series. If the DisplayName property is empty, then the legend uses a label of the form 'dataN' .

How to add legend title in MATLAB? ›

To add a legend title, set the String property of the legend text object. To change the title appearance, such as the font style or color, set legend text properties. For a list, see Text Properties. plot(rand(3)); lgd = legend('line 1','line 2','line 3'); lgd.

How do you edit the legend in MATLAB? ›

If you double-click on a text label in a legend, MATLAB opens a text editing box around all the text labels in the legend. You can edit any of the text labels in the legend. To access the properties of these text objects, right-click on a text label and select Properties from the context-sensitive pop-up menu.

What is the legend command used for? ›

The legend command produces a boxed legend on a plot, and labels each curve corresponding to different styles used. It has several optional arguments such as the following: legend(string1, string2,......) It produces legend specifying linestyle with each label.

How to add legend in MATLAB python? ›

Python has a function called legend() which is used to place a legend on the axis. The legend function has an attribute called loc which is used to denote the location of the legend. The default value of attribute loc is upper left. Other string, such as upper right, lower left, lower right can also be used.

What is legend () in Python? ›

legend() in Python. Matplotlib.pyplot.legend() function is a utility given in the Matplotlib library for Python that gives a way to label and differentiate between multiple plots in the same figure. The attribute Loc in legend() is used to specify the location of the legend.

How do you add a legend? ›

Click the chart, and then click the Chart Design tab. Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom. To change the format of the legend, click More Legend Options, and then make the format changes that you want.

How to add legend in matlab scope? ›

On the Scope tab, the Configuration section allows you to modify the scope. The Legend button turns the legend on or off. When you show the legend, you can control which signals are shown.

How do I show a specific legend in Matlab? ›

Specify Labels Using DisplayName

Alternatively, you can specify the legend labels using the DisplayName property. Set the DisplayName property as a name-value pair when calling the plotting functions. Then, call the legend command to create the legend. Legends automatically update when you add or delete a data series.

How to add legend to contour MATLAB? ›

clegendm( C , h ) adds a legend specifying the contour line heights, C , to the current map contour plot, h . clegendm( C , h , loc ) places the legend in a specified location. clegendm(___, unitstr ) appends a string unitstr to each entry in the legend.

How to write a title in MATLAB? ›

Create a plot. Then create a title and a subtitle by calling the title function with two character vectors as arguments. Use the 'Color' name-value pair argument to customize the color for both lines of text. Specify two return arguments to store the text objects for the title and subtitle.

What do you use a legend for? ›

A legend is used to identify data in visualizations by its color, size, or other distinguishing features.

Why do we use legend? ›

In web development, the <legend> element is used in HTML forms to provide a caption or a title for the associated <fieldset> element. It helps to visually group and describe the related form input elements within the fieldset.

What are legend keys? ›

Each legend key is a graphic that visually links a legend entry with its associated series or trendline in the chart. The legend key is linked to its associated series or trendline in such a way that changing the formatting of one simultaneously changes the formatting of the other.

What is the use of legend in graph? ›

Most charts use some kind of a legend to help readers understand the charted data. Whenever you create a chart in Excel, a legend for the chart is automatically generated at the same time. A chart can be missing a legend if it has been manually removed from the chart, but you can retrieve the missing legend.

What is the use of legend () function in R? ›

The in-built R function legend() can be used to add legend to plot. Parameters: x and y: These are co-ordinates to be used to position the legend.

What is the legend in math lab? ›

legend associates strings with the objects in the Axes in the same order that they are listed in the Axes Children property. By default, the legend annotates the current Axes. MATLAB displays only one legend per Axes. legend positions the legend based on a variety of factors, such as what objects the legend obscures.

How do you plot without a legend in MATLAB? ›

Below are two ways to remove a legend from a plot:
  • Use the "findobj" function to find the legend(s) and the "delete" function to delete them: % Find and delete the legend. lgd = findobj('type', 'legend') ...
  • If you do not want to delete the legend, you can turn off the legend's visibility: set(lgd(idx), 'visible', 'off')
Mar 26, 2016

Top Articles
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 5544

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.