how to give legend according to excel data headers

3 次查看(过去 30 天)
i am writing a gui code to plot the excel data having 352 rows and 4columns.Likewise i have multiple excel data sheets,which i have to change according to userspecification,so i had written ad code which allows me to choose any excel files and plot the graph acoordingly . now my problem is to give legend ,every time whenever ishould choose the file with the change of plots the legend should also change and they should be named after the excel headers .below is the code which i have written
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile({'*.xlsx'});
values = xlsread(strcat(pathname,filename));
x=values(:,1);
a=values(:,2);
b=values(:,3);
c=values(:,4);
hold on
plot(x,a,'r')
plot(x,b,'g')
plot(x,c,'b')
legend;
hold off
handles.xvalues=x;
handles.yvalues=a;
handles.yvalues=b;
handles.yvalues=c;
i do not know how to code legend according to excel headers

回答(1 个)

Voss
Voss 2022-4-23
One way to get the headers out of the .xlsx file:
[values,str_values] = xlsread('test.xlsx')
values = 5×4
0 1 2 3 1 3 5 8 2 2 4 6 3 5 7 9 4 4 4 6
str_values = 1×4 cell array
{'Variable 1'} {'Variable 2'} {'Variable 3'} {'Variable 4'}
How to apply that in your code:
function pushbutton1_Callback(hObject,eventdata,handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile({'*.xlsx'});
% values = xlsread(strcat(pathname,filename));
[values,str_values] = xlsread(strcat(pathname,filename));
x=values(:,1);
a=values(:,2);
b=values(:,3);
c=values(:,4);
hold on
plot(x,a,'r')
plot(x,b,'g')
plot(x,c,'b')
% legend();
legend(str_values(2:4));
hold off
handles.xvalues=x;
handles.yvalues=a;
handles.yvalues=b;
handles.yvalues=c;
guidata(hObject,handles); % <-- presumably you want to save the updated handles structure
end
You might have to do different or additional things, depending on the exact contents of your xlsx files.

类别

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