How do I display non-overlapping lines in one single MATLAB plot?

19 views (last 30 days)
I want to create a single plot showing non-overlapping lines, like the graph I have pasted here. When I try plotting the data with 'hold on', all the lines overlap. How can this be prevented?
  3 Comments
dpb
dpb on 23 Sep 2014
The first plot has a set of data that don't overlap at a give point on the x axis, to create a plot of that sort in Matlab just introduce a NaN in the vector of x,y data at the breakpoints.
The data that created the plot you show later doesn't have the same characteristics at all...don't know what you would expect it to look like instead.
Oh, unless the data were reversed and the four distinct x-values are supposed to be the sections of data. If that is the case, you should have columns of 8 values for either the four x values or, as noted above, splice them together w/ a NaN in between.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 23 Sep 2014
This will get you started:
Y1 = randi(6, 5, 4); % Create Data With 5 Columns of 4 Values Each
Y1 = Y1 + repmat([1:2:10]', 1, size(Y1,2)); % Add Constants to Simulate Data
Y2 = randi(6, 5, 4); % Create Data With 5 Columns of 4 Values Each
Y2 = Y2 + repmat([21:2:30]', 1, size(Y2,2)); % Add Constants to Simulate Data
X = linspace(1, numel(Y1), numel(Y1)); % Create X-Axis Vector
figure(1)
plot(X(1:4), Y1(1,:), '-ob', 'MarkerFaceColor','b')
hold on
for k1 = 2:size(Y1,1) % Loop for First Series
Xp = X(4*(k1-1)+1:4*(k1-1)+4);
plot(Xp, Y1(k1,:), '-ob', 'MarkerFaceColor','b')
end
for k1 = 1:size(Y2,1) % Loop for First Series
Xp = X(4*(k1-1)+1:4*(k1-1)+4);
plot(Xp, Y2(k1,:), '-sg', 'MarkerFaceColor','g')
end
hold off
xtiklbl_14s = repmat({'1' '2' '3' '4'}, 1, size(Y1,1));
set(gca, 'XTick', X, 'XTickLabel', xtiklbl_14s)
axis([xlim 0 50])
produces this plot:
Add a loop between the ‘hold on’ and ‘hold off’ lines for each data series. If you only have two series, then this should work as written. Note that the first for loop starts with 2 because the first row was the initial plot. The second for loop begins with 1.
Generating the ‘X’ vector may be a bit of a challenge, but not if you format your data like my ‘Y1’ and ‘Y2’ matrices, with a different row for each day, so that you have an (Nx4) array for each. (The both have to be the same size.) You can create the appropriate size arrays from vectors with the reshape function if your data are not already in that format. In that instance, ‘X’ will format itself and everything else should proceed without problems.
If you set up your ‘Y1’ and ‘Y2’ matrices as I did, this should run as written without problems.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!