Distance between axis label and axis in MATLAB figure

后端 未结 3 1063
后悔当初
后悔当初 2021-02-03 09:54

I\'m plotting some data with MATLAB and I\'d like to adjust the distance between axis label and the axis itself. However, simply adding a bit to the \"Position\" property of the

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-03 10:41

    I wrote a function that should do exactly what you want. It keeps the axes at the exact same size and position, it moves the x-label down and increases the figure size to be large enough to show the label:

    function moveLabel(ax,offset,hFig,hAxes)
        % get figure position
        posFig = get(hFig,'Position');
    
        % get axes position in pixels
        set(hAxes,'Units','pixels')
        posAx = get(hAxes,'Position');
    
        % get label position in pixels
        if ax=='x'
            set(get(hAxes,'XLabel'),'Units','pixels')
            posLabel = get(get(hAxes,'XLabel'),'Position');
        else
            set(get(hAxes,'YLabel'),'Units','pixels')
            posLabel = get(get(hAxes,'YLabel'),'Position');
        end
    
        % resize figure
        if ax=='x'
            posFigNew = posFig + [0 -offset 0 offset];
        else
            posFigNew = posFig + [-offset 0 offset 0];
        end
        set(hFig,'Position',posFigNew)
    
        % move axes
        if ax=='x'
            set(hAxes,'Position',posAx+[0 offset 0 0])
        else
            set(hAxes,'Position',posAx+[offset 0 0 0])
        end
    
        % move label
        if ax=='x'
            set(get(hAxes,'XLabel'),'Position',posLabel+[0 -offset 0])
        else
            set(get(hAxes,'YLabel'),'Position',posLabel+[-offset 0 0])
        end
    
        % set units back to 'normalized' and 'data'
        set(hAxes,'Units','normalized')
        if ax=='x'
            set(get(hAxes,'XLabel'),'Units','data')
        else
            set(get(hAxes,'YLabel'),'Units','data')
        end
    end
    

    In this case offset should be the absolute offset in pixels. If you want relative offsets, I think this function could easily be rewritten. hFig is the figure handle and hAxes the axes handle.

    EDIT: create the figure using hFig = figure; and the axes by hAxes = axes; (then set up the axes like you did in the question: set(hAxes,...)) before calling the function.

    EDIT2: added the lines where the 'Units' of hAxes and the XLabel are changed back to 'normalized' and 'data' respectively. That way the figure stays the way you want it after resizing.

    EDIT3: modified the function to work for both X and Y labels. Additional input ax should be 'x' or 'y'.

提交回复
热议问题