Include legends based on column names in for loop
이전 댓글 표시
Hi,
I have a loop which processes three tables. Each table has ten columns (in addition, each column includes column names). When I plot the three figures in the loop, I want to include legends which state the column name of each variable within the plot. I know how to make this manually by typing the legends in the Matlab code. However, since the column names are changing depending on table I want to perform this automatically in the script. My though is to use "Display" but I do not know how to apply this kind of approach. In terms of code procedure, I thought something similar to this (not working unfortunately):
vnames=Table_.Properties.VariableNames;
for v = 1:numTables
%Processing of the code
plot(Table_.Col1,Table_{:,3},'DisplayName',vnames(v))
legend show
end
Grateful for any advice.
채택된 답변
추가 답변 (1개)
Mathieu NOE
2022년 1월 12일
hello
see my little demo below to use the table varibales names as legend
the csv data file is attached
clearvars
clc
%get the data from table
T = readtable('pH_Data.csv'); %Reads Table or CSV File
vnames=T.Properties.VariableNames; % {'DateAndTimeRun1'} {'Time_s_Run1'} {'Voltage_mV_Run1'} {'pHRun1'}
time = T.Time_s_Run1; % time (s)
data = table2array(T(:,3:end)); % data
plot(time,data);
lgstr = vnames(3:end); % use vnames to make legend strings
% legend strings convert underscore to blanks for better legend readability
for ck = 1:numel(lgstr)
tmp = char(lgstr(ck));
ind = strfind(tmp,'_');
tmp(ind) = ' ';
lgstr{ck} = tmp; % update
end
legend(lgstr);

댓글 수: 7
Vlatko Milic
2022년 1월 12일
Vlatko Milic
2022년 5월 16일
Mathieu NOE
2022년 5월 16일
hello again
can you share some data and code ? I'll have a look if I get it to work !
Vlatko Milic
2022년 5월 16일
Mathieu NOE
2022년 5월 16일
hello
try this :
T = readtable('m.xlsx');
matchVals = {'1234', '5678','9101','1123'};
n_match = numel(matchVals);
% S = struct('name',matchVals,'data',cell(1,n_match)); % what is this for ?
%
vnames=T.Properties.VariableNames; % added this line
for k = 1:n_match
idx = contains(T.Properties.VariableNames,matchVals{k});
figure
plot(1:1:10000,T{:,idx})
fig_name = strcat('Box_',num2str(matchVals{k}));
title(fig_name,'Interpreter','none')
legend(vnames(idx)); % added this line
end
Vlatko Milic
2022년 5월 16일
Mathieu NOE
2022년 5월 16일
My pleasure !
카테고리
도움말 센터 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
