MATLAB:在图形底部添加图例,而不更改图形宽度或调整绘图大小

MATLAB:在图形底部添加图例,而不更改图形宽度或调整绘图大小,matlab,matlab-figure,Matlab,Matlab Figure,我经常遇到与MATLAB绘图中的图例有关的问题,我想想出一种方法来避免在将来出现这些问题 我想做的是: 创建具有固定大小的地物: f=figure('Position',[0 0 800 600]) 画出我想在这个图中画的东西 x=-pi:0.01:pi 绘图(x,sin(x),x,cos(x),x,tan(x)) 将图例添加到图形底部的绘图中,而不调整绘图的大小(可以说,我可以将图形设置为“更高”,但我希望图例在绘图、轴和其他所有位置都能显示出来)。如果可能,我还希望使用包创建图例(不确定这是

我经常遇到与MATLAB绘图中的图例有关的问题,我想想出一种方法来避免在将来出现这些问题

我想做的是:

  • 创建具有固定大小的地物:

    f=figure('Position',[0 0 800 600]

  • 画出我想在这个图中画的东西

    x=-pi:0.01:pi
    绘图(x,sin(x),x,cos(x),x,tan(x))

  • 将图例添加到图形底部的绘图中,而不调整绘图的大小(可以说,我可以将图形设置为“更高”,但我希望图例在绘图、轴和其他所有位置都能显示出来)。如果可能,我还希望使用包创建图例(不确定这是否会引发任何问题)


  • 有人知道我该怎么做吗?

    我使用的是倍频程,而不是MATLAB,但是下面的工作(或者至少让你更接近你想要的)

    阿诺

    % Create the figure and plot
    f = figure('Position',[0 0 800 600]);
    x = -pi:0.01:pi;
    plot(x,sin(x),x,cos(x),x,tan(x));
    
    % Set axes and figure units to pixels, get current positions
    set(f,'Units','pixels')
    set(gca,'Units','pixels')
    fig_pos = get(f,'position');
    old_ax_pos = get(gca,'position');
    
    % Add a legend et get its position too
    h = legend('L1','L2','L3','location','southoutside');
    set(h,'Units','pixels')
    leg_pos = get(h,'position');
    
    % Get the new axes position, look at how much it shifted
    new_ax_pos = get(gca,'position');
    pixel_shift = new_ax_pos - old_ax_pos; % y position shift is positive (axes moved up), y height shift is negative (axes got smaller)
    
    % Make figure taller and restore axes height to their initial value
    set(f,'position',fig_pos - [0 0 0 pixel_shift(4)]);
    set(h,'position',leg_pos)
    set(gca,'position',old_ax_pos + [0 pixel_shift(2) 0 0])
    
    % Create a new figure without legend for comparing
    f2 = figure('Position',[0 0 800 600]);
    x = -pi:0.01:pi;
    plot(x,sin(x),x,cos(x),x,tan(x));