Erratic behavior of Matlab's legend function - matlab

I was working on a MATLAB project and found some strange behavior of the legend function. Here is the code to reproduce the issue:
X=rand(3,100);
a=rand(3,100);
b=rand(3,100);
figure(1); hold on;
plot(0.17663,'m');
plot(1.223,'y');
plot(X,a,'r');
plot(X,b,'g');
legend({'s1','s2','a','b'});
My question is: The legend in the picture shows the same color for plot 3 and plot 4. Instead it should show red and green respectively. Is there something wrong with legend?

The commands plot(X,a,'r') and plot(X,b,'g') are not what you might expect. As X is a 3-by-100 array they will plot 100 lines, each consisting of 3 points, start, middle, end. The legend entries will correspond to each single line, so you should expect 100 red legend entries. You will see different behavior if you pass transposed arrays: plot(X.',a.','r'). This will plot 3 lines, each consisting of 100 points.

Related

Legend each curve in a single figure from a matlab plot

I want to plot four curves in a single figure from matlab, so I am using hold on. Furthermore, I want to create an legend to each curve, so I wrote the code:
clear all
x=linspace(0,10,100);
x2=linspace(-5,15,100);
x3=linspace(-10,20,100);
x4=linspace(35,40,100);
figure(1)
plot(x,x2)
legend('x2')
hold on
plot(x,x3)
legend('x3')
hold on
plot(x,x4)
legend('x4')
hold on
plot(x,x)
legend('x')
hold off
But the result is that all my curves are in the same color, and just the last legend "x" has appeared in the figure (see it below).
How can I set one legend to each curve? All curves must have different colors.
This depends a bit on your matlab version. In older versions (and in octave), plots added through the use of hold on get the same color. In R2015b (i don't know when this was introduced), the individual plots get different colors, but still only one legend is displayed.
To get multiple colors and multiple legend entries, you can specify all data to be plotted in one call, the same for the legends:
plot(x, x, x, x2, x, x3, x, x4);
or
plot(x, [x', x2', x3', x4']);
For the legends, approach the same way:
legend('x', 'x2', 'x3', 'x4');
If you want to build up a legend without knowing the number of entries before hand, you would want to search for "dynamic legends". See for example here:
http://undocumentedmatlab.com/blog/legend-semi-documented-feature

How to plot contours with selected colors and formatted labels

I'm trying to plot contour using my computed data with limited contour labels and and colors as given in the top panel of this image:
But I ended up with a slightly different plot (see the plot in the bottom of the above image).
I want to modify my plot with the following three specifications
Restrict contour labels in 2 or 3 decimal places
Remove plot labels in the area where the contours are too close to each other.
Plot with two colors as in the first image
Here is my code:
f=load('fort.15');
ngridx=180;
ngridy=180;
x=f(:,3);
y=f(:,4);
z=f(:,5);
xlin=linspace(min(x),max(x),ngridx);
ylin=linspace(min(y),max(y),ngridy);
[X,Y]=meshgrid(xlin,ylin);
Z=griddata(x,y,z,X,Y,'linear');
[c,h] = contour(X,Y,Z,20);
set(h,'LineWidth',2,'LineColor',rgb('SteelBlue'),'ShowText','on',...
'LabelSpacing',800 )
axis([0 6 -5 7])
I'm not an expert in Matlab. Please help me get the right plot.
I'm attaching my data file here.
Well, I got only 2 of 3. Deine the level in which the color has to change (here scl) and you good to go:
scl = 6.5; % switch color level;
[c1,h1] = contour(X,Y,Z,scl:max(Z(:)),'Color','r');
hold on
[c2,h2] = contour(X,Y,Z,min(Z(:)):scl,'Color','b');
clabel(c2,h2);
axis([0 6 -5 7])
The idea here is to builed your plot from two contour objects, using hold on command. the vector scl:max(Z(:)) define the levvels to show in the first contour, and the get the red color and no lables. And a similar logic works for the secound contour.
If you want to lable some red contours, or remove lables from the blue ones, you need to replace h2 in the clabel function with a vector of the levels you want to lable. If you will be mo specific in the comments I'll update my answer.
Changing the formatting of the lables, is probably possible somehow, but it's really not trivial, so I left it by now.

plot multiple 3d lines

I'm trying to plot 2 lines in a single 3D graph. I have 3 coordinate data matrices for each line.
This is my code:
plot3(pathline_x1 , pathline_y1 , pathline_z1,'g');
hold on
plot3(pathline_x1,pathline_y1,pathline_z1,'r');
hold on
From some reason it plots only the last one. Can someone help me plot both lines?
x = [1 2];y=x;
figure;plot(x,y,'r');hold on;plot(x,y,'b');
This will overwrite your line, since x and y are exactly equal.
To see it actually works, plot two different lines:
figure;plot(x,y,'r');hold on;plot(x,y+2,'b');
Note that I have called hold on only once, since it will hold all plots within the figure until you call hold off or open a new figure using figure.

Matlab legend colors don't match lines

Not sure what is going wrong here. I created a minimal example below:
clear
steps = 1:6;
labels = cell(length(steps),1);
xvals = 1:10;
fig = figure(1);
ax = axes('parent',fig);
hold on
for ii=1:length(steps)
s=steps(ii);
yvals = zeros(length(xvals)) + ii;
labels{ii} = ['gain = ' num2str(s)];
plot(ax,xvals,yvals);
end
legend(ax, labels);
hold off
And the result on my system is:
With less lines it can even put colors in the legend that aren't even on the plot. What is happening?!
Explanation of what's happening
The problem is in the line
yvals = zeros(length(xvals)) + ii;
This creates a 10x10 square matrix, not a 1x10 vector. plot then plots each column of that matrix against xvals. That causes a mixing up of colors which is probably not what you want.
It's interesting to analyze specifically what happens. Matlab plots each column of that matrix with a different color, using the default cycle of colors, which in Matlab R2014b onwards is
But all columns of that matrix are the same, so each covers (overwrites) the preceding one, and you only see the last color.
Now, the color cycle has 7 colors and the matrix has 10 columns. So in the first iteration the last plotted column (the one you see) has color mod(10,7)==3 (yellow). In the second iteration you cycle through 10 more colors starting from 3, that is, you get color mod(3+10,7)==6 (light blue). And so on. Thus the color you see in the figure depends on the loop index ii, but not in the way you expected.
legend creates its entries by picking the color (and line spec) of each plotted line, in the order in which they were plotted. There are 10*6==60 plotted lines, each corresponding to a column of a matrix. But since you only supply six strings to legend, it just picks the first six of those lines, and uses their colors to create the legend entries. Those colors follow the default order, as explained above.
None of those first six lines that make it into the legend are actually seen in the figure, because they are covered by other lines. But legend doesn't care about that. So you get six legend entries with the default color order, which of course doesn't match the lines you actually see in the graph.
Solution
From the above, the solution is clear: replaced the referred line by
yvals = zeros(1, length(xvals)) + ii;
to create yvals as a vector (not a matrix). That way you'll get the figure you expected:

Changing axes and color of plots in Matlab

How do you get rid of the axes and dotted line grids when you plot in Matlab? Also, how do I make subplots of subplots. Since that's probably not very clear, what I mean is the following...
Let's say I have a 10x10x10 .mat file, so I open each of the 10 frames and plot what I have on each 10x10 frame. I generate 2 different plots for each frame so that in total there are 20 plots. For each frame I generate 2 subplots. When I run the code, I get 10 different figures with 10 subplots. I'd like to get for this example 1 figure with 20 subplots where the first two refer to the first iteration, second two refer to the second, etc.
for i = 1:10
z=z(:,:,i);
figure(i)
subplot(1,2,1)
surf(z)
%code, obtain new array...
subplot(1,2,2)
surf(new)
end;
You can hide the axes with
set(gca,'Visible','off')
And if you want 20 subplots, try the following:
for i = 1:10
z=z(:,:,i);
subplot(10,2,2*i-1)
surf(z)
%code, obtain new array...
subplot(10,2,2*i)
surf(new)
end
When you use figure(i), you're referring to Figure i which will be created if it does not exist. And with subplot you can specify the ordering of the subplots with the first two arguments.
Note:
20 subplots on one figure are not going to be pretty --- you probably won't be able to see anything, so you should probably break it up into several figures.