简体   繁体   中英

MATLAB plot: automatically using a column variable (Name) as Display Name in the legend

So I have a series of temperature loggers which all have a specific name and I want to plot them as follows:

情节的例子

Now, as you can see in the example plot I added, the legend automatically labels the lines as data1, data2, data3,... . However, I need the legend to show the names of the loggers. Because there are many loggers, I need MATLAB to do it automatically because it would take hours to use DisplayName and type in every logger name manually. Does anyone know how I can chose a column in my data table as the name for my lines? My table is built as follows:

Name of logger 1| Date | Temperature | Name of logger 2 | Date | Temperature % and so on

This is part of the code I use for the plots:

hold on
for i=2:2:35
   plot(data{:,1}, data{:,i})
end
hold off

structure of the

You can use the DisplayName argument of plot , together with dynamically retrieving the table variable names, to do this automatically.

vNames = data.Properties.VariableNames;
for ii = 2:2:35
    plot( data{:,1}, data{:,ii}, 'DisplayName', vNames{ii} );
end

Now when you call legend , the series will be named according to the table variable names.


Note that once you've got the variable names, you can equivalently index the table with them (instead of ii directly) like so:

vNames = data.Properties.VariableNames;
for ii = 2:2:35
    plot( data.Date, data.(vNames{ii}), 'DisplayName', vNames{ii} );
end    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM