plot multiple data from excel with legend

10 vues (au cours des 30 derniers jours)
Yuktha Andie Ravinthiran
Yuktha Andie Ravinthiran le 17 Fév 2022
Réponse apportée : Rahul le 8 Nov 2024 à 8:57
p2 = 'filename.xlsx'
hold on
x1 = xlsread(p2,'1','E2:E37');
y1 = xlsread(p2,'1','C2:C37');
%..... other x and y data
x10 = xlsread(p2,'1','E326:E361');
y10 = xlsread(p2,'1','C326:C361');
eplot = plot(x1,y1,'r-.',x2,y2,'y',x3,y3,'g',x4,y4,'c',x5,y5,'b',x6,y6,'m',x7,y7,x8,y8,x9,y9,x10,y10);
legend('1','2','3','4','5','6','7','8','9','10')
hold off
Is there a way to specify all my x data is from E2:E361 but still make it plot 10 different lines by specifying the range of each line's number of x values
I would like to use 1:length(line colour) but don't know how it works
I also can't change the colour of a line to orange even after using the hexdecimal for it eventhough I use R2021a
eplot = plot(x1,y1,'r-.',x2,y2,'#D95319')

Réponses (1)

Rahul
Rahul le 8 Nov 2024 à 8:57
To achieve the desired plot after reading data from an ‘xlsx’ file, you can use the 'readmatrix' function with 'Sheet' argument while obtaining the entire range of x and y data. Here is an example:
p2 = 'filename.xlsx'
x_data = readmatrix(p2, 'Sheet', 1, 'Range', 'E2:E361');
y_data = readmatrix(p2, 'Sheet', 1, 'Range', 'C2:C361');
Then you can define the number of points per line and cell arrays to hold the data.
points_per_line = 35; % Adjust this based on your specific data
x_lines = cell(1, 10);
y_lines = cell(1, 10);
Then using a loop you can populate the cell array sequentially.
for i = 1:10
start_idx = (i - 1) * points_per_line + 1;
end_idx = i * points_per_line;
x_lines{i} = x_data(start_idx:end_idx);
y_lines{i} = y_data(start_idx:end_idx);
end
Finally you can make use of 'Color' and 'Linestyle' properties of 'plot' function to correctly define colors of each data range and style. Here is an example:
hold on
colors = {'r', 'y', 'g', 'c', 'b', 'm', '#D95319', 'k', 'b', 'm'};
lineStyles = {'-.', '-', '-', '-', '-', '-', '-', '-', '-', '-'};
for i = 1:10
plot(x_lines{i}, y_lines{i}, 'Color', colors{i}, 'LineStyle', lineStyles{i});
end
legend('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
hold off
You can refer to the following MathWorks documentations to know more about these functions:
Hope this helps! Thanks.

Community Treasure Hunt

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

Start Hunting!

Translated by