Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add legend outside of axes without rescaling in MATLAB

I've got a GUI in MATLAB with a set of axes pre-placed. I'm using the location property of the legend to place it to the right hand side of the axes. However, by doing this the axes get re-scaled so that the axes+legend take up the original width of the axes. Is there any way to circumvent the re-size?

Example:

x=0:.1:10;
y=sin(x);
figure
pos=get(gca,'position');
pos(3)=.5; %#re-size axes to leave room for legend
set(gca,'position',pos)
plot(x,y)

So far I get:

alt text

Place legend:

legend('sin(x)','location','eastoutside')

...aaaaand...

alt text

MATLAB squishes it all into the original axes space. Any way around this?

like image 792
Doresoom Avatar asked Aug 30 '10 17:08

Doresoom


People also ask

How do you add a legend to an outside plot in MATLAB?

To add a legend title, set the String property of the legend text object. To change the title appearance, such as the font style or color, set legend text properties. For a list, see Text Properties. plot(rand(3)); lgd = legend('line 1','line 2','line 3'); lgd.

How do I manually add a legend in MATLAB?

Legend Font Size and Title Then, use lgd to change the properties using dot notation. x1 = linspace(0,5); y1 = sin(x1/2); plot(x1,y1,'DisplayName','sin(x/2)') hold on x2 = [0 1 2 3 4 5]; y2 = [0.2 0.3 0.6 1 0.7 0.6]; scatter(x2,y2,'filled','DisplayName','2016') hold off lgd = legend; lgd. FontSize = 14; lgd.

How do you make a legend outside the plot?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.

How do you organize a legend in MATLAB?

By default the order of the lines in the legend is the same as they are plotted. The easiest way is to just plot them in the order you want the legend to appear. If that is not feasible, then you can change the order of the lines as they are stored in the 'Children' property of the axes.


Video Answer


1 Answers

EDIT

%# create three axes with custom position
x=0:.1:10;
y=sin(x);
hAx1 = axes('Position',[0.05 0.05 0.7 0.2]); plot(hAx1, x,y)
hAx2 = axes('Position',[0.05 0.4 0.7 0.2]); plot(hAx2, x,y)
hAx3 = axes('Position',[0.05 0.75 0.7 0.2]); plot(hAx3, x,y)

%# add legend to middle one
h = legend(hAx2, 'sin(x)'); pos = get(h,'position');
set(h, 'position',[0.8 0.5 pos(3:4)])

alt text

like image 133
Amro Avatar answered Nov 16 '22 00:11

Amro