Search code examples
matlabplotgraphing

MATLAB: Trying to add shared xlabel,ylabel in 3x2 subplot


As the title says, what I am pretty to do is fairly straight forwards. I have a grid of m=3,n=2 subplots. They represent graphs of 6 different experiments measuring the same parameters. I would like to have a single x label and a single y label on the border of the six subplots. Unfortunately, I have not been able to dig up a simple way to do this so far. (xlabel simply puts an xlabel under the last active subplot). Anyone know how this can be done?

Oh, and how would I display degrees Celsius in the label with the degrees symbol?(the little circle...)


Solution

  • You could use mtit to create an invisible axes around the subplots. mtit returns the handle to that axes, for which you can then create xlabel and ylabel.

    Example:

    % create sample data
    my_data = arrayfun(@(x)rand(10, 2) + repmat([x, 0], 10, 1), 1:6, 'UniformOutput', 0);
    
    figure;
    clf
    ah = gobjects(6, 1); % use zeros if using an old version of MATLAB
    % plot data
    for ii = 1:6
        ah(ii) = subplot(3, 2, ii);
        plot(1:10, my_data{ii}(:, 1));
        hold on
        plot(1:10, my_data{ii}(:, 2));
    end
    % link axes to have same ranges
    max_data = max(cellfun(@(x) max(x(:)), my_data));
    min_data = min(cellfun(@(x) min(x(:)), my_data));
    linkaxes(ah, 'xy')
    ylim([min_data, max_data])
    
    % Create invisible large axes with title (title could be empty)
    hh = mtit('Cool experiment');
    %set(gcf, 'currentAxes', hh.ah)
    % make ylabels
    ylh = ylabel(hh.ah, 'Temperature [°C]');
    set(ylh, 'Visible', 'On')
    xlh = xlabel(hh.ah, 'x label');
    set(xlh, 'Visible', 'On')
    

    This will produce a figure like this one: Example output