How to make a simple plot with two lines?
Show older comments
Hi. I am new to MatLab. I want to make a plot with two lines for 2001 and 2003 group of schoolyear vs students. (Please note, not "year", but "schoolyear"). The x-axis would have the 12 months of the year, and the y-axis has the students.
table_a = readtable('Data1.xlsx');
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
% how do I make a single plot with two lines, one for 2001 and one for
% 2003. It would be a time series, the month would be on the x-axis, and
% students would be on the y-axis.
Accepted Answer
More Answers (2)
Venkat Siddarth
on 9 Feb 2023
I understand that you are trying to plot two lines in a single axis with x-axis as months and y-axis as corresponding students in the respective years. This can be achieved as follows:
%Firstly,load the data and add the "schoolyear" column
table_a = readtable('Data1.xlsx');
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
After that we will obtain the data in the form of vector using curly brackets({})
%obtaining and sorting months and corresponding students data with schoolyear 2001
data_2001=sortrows(table_a{table_a{:,"schoolyear"}==2001,["month" "students"]},1);
%obtaining and sorting months and corresponding students data with schoolyear 2003
data_2003=sortrows(table_a{table_a{:,"schoolyear"}==2003,["month" "students"]},1);
After that we plot the data using plot function and using the command hold on we create the plots on same axis.
plot(data_2001(:,1),data_2001(:,2),"s-");
hold on
plot(data_2003(:,1),data_2003(:,2),"o-");
legend(["2001" "2003"])
hold off
I hope this resolves your query.
Thanks,
Venkat Siddarth V
Macy
on 9 Feb 2023
0 votes
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!