首页 文章

MATLAB:在不改变图形宽度或调整图形大小的情况下在图形底部添加图例

提问于
浏览
0

我在MATLAB图中经常遇到传说中的问题,并希望在将来想出一种方法来避免它们 .

我想做的是以下内容:

  • 创建一个固定大小的数字:

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

  • 绘制我希望在此图中绘制的任何内容

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

  • 在图的 bottom 处添加一个图例,而无需调整图表的大小(我很好地使图"taller"可以这么说“,但我希望图例能够获得图表,轴和其他所有内容)如果可能的话,我还想使用legendflex包创建图例(不确定这是否会引起任何问题) .

有谁知道我怎么能这样做?

1 回答

  • 2

    我使用Octave而不是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));
    

    阿尔诺

相关问题