How can I order items in a Matlab legend via the figure editor? - matlab

I've created a histogram with multiple sets of data. The data sets are color imgages converted to grayscale and taken over a given time period (e.g. pic 1 # time=0, pic 2 # time=5min, etc.) which is why I need the legend entries to show up in a specific order. When I put the legend in, the entries are scattered around in no specific order and I can't figure out how to get the entries switched up the way I need them.

In 2017a and higher (using part of the answer by Peter M above)
Select "Edit Plot" with the standard arrow button in the toolbar. This will allow you to select plot lines.
Select the plot line you want to appear first in the legend.
Use Ctrl-X (or whatever on OS X,Linux) to "Cut" the Plot line.
Create a new figure (File -> New -> Figure).
Use Ctrl-V (or whatever on OS X, Linux) to "Paste" the Plot line in the new figure.
"Cut" the Plot line in the new figure.
"Paste" the Plot line in the original figure.
Repeat steps 2-6 for every plot line, in the order that you want
them to appear in the legend. Right click on the legend and
"Refresh"

If you are regenerating the plot often of course it is probably a good idea to make sure that the script puts them in the correct order. Luis Mendo provided an answer here, but his answer to a slightly different wording was a little more detailed: how to change the sequence of the legend.
Pre 2017a Only! It seems that 2017a breaks this behavior, so the following trick does not work in the latest versions.
To answer your specific question, here is a neat trick if you are just doing this once in awhile on a plot that doesn't have many lines, and only want to use the Figure Editor...
Select "Edit Plot" with the standard arrow button in the toolbar. This will allow you to select plot lines.
Select the plot line you want to appear first in the legend.
Use Ctrl-X (or whatever on OS X, Linux) to "Cut" the Plot line.
Use Ctrl-V (or whatever on OS X, Linux) to "Paste" the Plot line.
Repeat steps 2-4 for every plot line, in the order that you want them to appear in the legend.
Right click on the legend and "Refresh"

You can get a handle to each plotted object, and in the legend use the handles to control which string applies to which plotted object.
Example:
h1 = plot(1:5, 1:5, 'r');
hold on
h2 = plot(1:5, 2:6, 'b');
legend([h1 h2],'First red','Second blue')

The answer above also works for R2017a and higher...here is a little bit more general example:
x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
figure
plot(x, y1, x, y2, x, y3, x, y4);
lh = legend('y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2');
legendEntries = get(gca,'legend')
plotHandles = get(gca,'children')
legendEntries = legendEntries.String;
newOrder = [3,4,1,2];
legend([plotHandles(newOrder)],legendEntries{newOrder})

flipud(h) or fliplr(h) to change complete order of the array up-down oder left-right

Through try and error I found this easy fix:
1) select the plot line that should be at position 1 (at the top)
2) Strg + X
3) Strg + V in the same plot figure
Repeat step 2 and 3 about 3 or 4 time. This will result in the plot beeing at the bottom of the legend. Now select the plot that should be at the 2nd position, again Step 2 and 3 a couple times. The previous plot moves one place up, the 2nd picked plot is now at the bottom.... continue with the rest of the plots the same way

Related

How to switch display of x & y values on a MATLAB plot, without switching plot() args

Consider the following code:
x = 0:0.1:pi;
y = sin(x);
plot(x,y)
I want to switch the display of this plot, such that x displays on the vertical axis and y displays on the horizontal axis.
Obviously for this example, the easiest way is to plot(y,x). However in my actual code I'd have a ton of plot calls to edit among several functions, and I want to switch back and forth easily. It's a bird's eye East-North plot, and some experiment geometries don't come out very well with East on the x axis.
Thanks in advance!
what you want is to toggle between views after selecting the axes of you plot.
For example, say you run your code and have a bunch of plots on the screen. You choose the plot you want to flip by clicking on the empty space within the plot box. Then you type in the command line some function name that is designed to flip the plot.
This function can be view ( view(90,90) or view(0,90) ), or a generic function such as:
function flipplot
h=get(gca);
xd=h.Children.XData;
yd=h.Children.YData;
h.Children.XData=yd;
h.Children.YData=xd;
end
you can save that flipplot function as flipplot.m, then each time you do the above (select a plot with your mouse etc) and enterflipplot on the command line you get what you want.

How to change font size of right axis of Pareto plot in Matlab

I am trying to bold the right side y axis for a Pareto plot in Matlab, but I can not get it to work. Does anyone have any suggestions? When I try to change the second dimension of ax, I get an error:
"Index exceeds matrix dimensions.
Error in pcaCluster (line 66)
set(ax(2),'Linewidth',2.0);"
figure()
ax=gca();
h1=pareto(ax,explained,X);
xlabel('Principal Component','fontweight','b','fontsize',20)
ylabel('Variance Explained (%)','fontweight','b','fontsize',20)
set(ax(1),'Linewidth',2.0);
set(ax(1),'fontsize',18,'fontweight','b');
%set(ax(2),'Linewidth',2.0);
%set(ax(2),'fontsize',18,'fontweight','b');
set(h1,'LineWidth',2)
Actually you need to add an output argument during the call to pareto and you will then get 2 handles (the line and the bar series) as well as 2 axes. You want to get the YTickLabel property of the 2nd axes obtained. So I suspect that in your call to pareto above you do not need to supply the ax argument.
Example:
[handlesPareto, axesPareto] = pareto(explained,X);
Now if you use this command:
RightYLabels = get(axesPareto(2),'YTickLabel')
you get the following (or something similar):
RightYLabels =
'0%'
'14%'
'29%'
'43%'
'58%'
'72%'
'87%'
'100%'
What you can do is actually to erase them altogether and replace them with text annotations, which you can customize as you like. See here for a nice demonstration.
Applied to your problem (with dummy values from the function docs), here is what you can do:
clear
clc
close all
y = [90,75,30,60,5,40,40,5];
figure
[hPareto, axesPareto] = pareto(y);
%// Get the poisition of YTicks and the YTickLabels of the right y-axis.
yticks = get(axesPareto(2),'YTick')
RightYLabels = cellstr(get(axesPareto(2),'YTickLabel'))
%// You need the xlim, i.e. the x limits of the axes. YTicklabels are displayed at the end of the axis.
xl = xlim;
%// Remove current YTickLabels to replace them.
set(axesPareto(2),'YTickLabel',[])
%// Add new labels, in bold font.
for k = 1:numel(RightYLabels)
BoldLabels(k) = text(xl(2)+.1,yticks(k),RightYLabels(k),'FontWeight','bold','FontSize',18);
end
xlabel('Principal Component','fontweight','b','fontsize',20)
ylabel('Variance Explained (%)','fontweight','b','fontsize',20)
which gives this:
You can of course customize everything you want like this.
That is because ax is a handle to the (first/left) axes object. It is a single value and with ax(1) you got lucky, its ax again, but ax(2) is simply not valid.
I suggest to read the docs about how to get the second axis. Another good idea always is to open the plot in the plot browser, click whatever object you want so it is selected and then get its handle by typing gco (get current object) in the command window. You can then use it with set(gco, ...).

Paint each graph trace the same color in MATLAB

I have the following MATLAB code and I'm trying to make all of the plot traces black:
x = 20:0.01:30;
m1 = 25;
s1 = 2.5;
pdfNormal_1 = normpdf(x, m1, s1);
m2 = 25.478;
s2 = 0.1637;
pdfNormal_2 = normpdf(x, m2, s2);
m3 = 25.478;
s3 = 0.189;
pdfNormal_3 = normpdf(x, m3, s3);
set(gcf,'color','w');
g=findobj(gca,'Type','patch');
%set(g(1),'FaceColor',[0 .5 .5],'EdgeColor','w')
%set(g(2),'FaceColor',[0 1 1],'EdgeColor','w')
%set(g(3),'FaceColor',[0 1 1],'EdgeColor','w')
set(gca,'Fontsize',12,'Fontname','euclid')
xlabel(' ') %título eixo xx
hold all;
%plot(x, pdfNormal_1, x, pdfNormal_2, x, pdfNormal_3);
%set(gcf,'Color',[0 0 0])
plot(x,pdfNormal_1,'-.')
plot(x,pdfNormal_2,':')
plot(x,pdfNormal_3,'-','LineWidth',2)
Can someone help me? I removed the % from set(...);, but it plots nothing.
I don't quite know what exactly you want. You can either interpret this as:
You wanting all of your lines to be black
You wanting the background pane to be black.
Let's answer each question anyway so we have our bases covered.
Wanting all lines black
For the third parameter in plot, you can use a single letter that specifies what colour you want for your lines within your plot. Therefore, if you want all three of your plots black, use k after each invocation to plot. b is actually reserved for blue. Also, because you are calling plot more than once, each call to plot by default will overwrite the contents of the current figure with the latest invocation to plot, and so if you want all three plots to appear at the same time, you need to use hold on. Therefore, place this at the end of your code:
hold on;
plot(x,pdfNormal_1,'k-.')
plot(x,pdfNormal_2,'k:')
plot(x,pdfNormal_3,'k-','LineWidth',2);
You can also get rid of any set commands as these aren't useful. What you're actually doing is setting the background of the figure to white, which is probably not what you want to do. By background, I mean the area where the axes appear, not the drawing area of the plot itself.
Wanting the background pane black
If you want the background of where the plot appears to be black, it's a very simple one line statement. You need to set the current axes colour, not the current figure. Therefore, replace your set(gcf...) statement with set(gca...). Therefore:
set(gca,'Color',[0 0 0])
Now, if this is what you want, it'll be up to you to figure out what colours will appear on this plot nicely. Red certainly appears nice here!
For more information about how plot works, check out the documentation page on MathWorks: http://www.mathworks.com/help/matlab/ref/plot.html. It's actually very well explained!

matlab bar plot: labeliing 3 bars with each only one value

I need to make a bar graph in matlab with 3 bars. The values for the three bars is stored in x. Now I want a to make a legend: Each bar should be labeled with a letter e.g. 'A','B','C'.
x = rand(1,3); bar(x); legend('A','B','C');
Did not work.
Then I tried this example: http://www.mathworks.com/matlabcentral/fileexchange/35271-matlab-plot-gallery-vertical-bar-plot/content/html/Vertical_Bar_Plot.html
But as soon as you reduce the the number of entries in each category to 1, you'll get an error message, but I think the message is wrong =/ it works with any number but just not with 1...
So is there a simple solution to that problem?
What you want is a "three series plot" - unfortunately, as soon as you make it 1x3, Matlab thinks it's just a single series. We have to trick it into thinking you have three series. Here's how you do that:
x = rand(1,3);
x2 = [x; x*0]; % add a second row of all zeros
figure
bar(x2); % now we have a plot with an ugly second category
xlim([0.5 1.5]); % trick that hides second category
legend('a','b','c'); % add the legend
set(gca, 'XTickLabel', ''); % hide the '1' on the X axis (or make it whatever you want)
title 'Bar plot with legend - demo'
Result is then something like this:
I believe this is exactly what you were asking for.

How to display slope on a plot in Matlab

I used the regress function to find the slope for some data I plotted. I have managed to plot the data and the fitted line both on the same plot. I know how to make it clear that the fitted line is the slope, but I would also like to add a box in corner of the graph (dont care where) that shows the actual value of the slope (basically shows the value that the regress function returns), and I'm trying to find a way to do this automatically (like if there's a function for that or something). Can anybody help (I hope I explained my question well enough...)?
I didn't try to recreate your slope line but have you considered using an annotation?
Example:
x = [-1:.2:1];
plot(x,x.^2,'-bo');
annotation('textbox', [.4 .4 .1 .1], 'String', ...
['slope at x = 0.6 is: ',num2str(2*.6)]);
Which shows:
Of course you can control how the box is positioned, formatted, and so forth.
Check the help files for more detailed info. In some cases you might also consider using a legend().
The function text adds text to a figure. It requires a position and a string to display. In addition, you can highly customize the appearance of the text. For example:
x = 1:100;
y = randn(size(x)) + 0.3*x;
plot(x,y,'.');
p = polyfit(x,y,1);
hold on;
plot(x, polyval(p,x),'k-');
h = text(min(xlim(gca)), max(ylim(gca)), ...
sprintf('%fx + %f', p(1), p(2)),...
'verticalalignment','top',...
'horizontalalignment','left');
Then, to see the various settinsg you can change, look at:
get(h)
Those properties can almost all be changes at creation (like verticalalignment above) or after creation (e.g. set(h, verticalalignment, 'top')).