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

6.2k views Asked by At

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...)

3

There are 3 answers

0
zeeMonkeez On BEST ANSWER

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

0
il_raffa On

I do not know what is the error you've got in setting xlabel and ylabel to each subplot.

Also I'm not sure I've understood problem.

The following code, generates 3x2 subplot each of them with its xlabel and ylabel.

In the first case each subplot has a different string for xlabel and ylabel.

In the second one the same xlabel and ylabel are set for all the subplos.

To add the "°" sign to the label, it is sufficient to define a char variable this way:

c='°'

then to use sprintf to generate the string for the xlabel and ylabel.

a=randi(100,6,20)

figure

% Each subplot with its own xlabel and ylabel
for i=1:6
   hs(i)=subplot(3,2,i);
   plot(a(i,:))
   c='°'
   str=sprintf('Temp [C%c]',c)
   xlabel([str ' ' num2str(i)])
   ylabel(['Subplot ' num2str(i)])
   grid on
end

figure

% The same xlabel and ylabel for all the subplot
c='°';
x_label_str=sprintf('Temp [C%c]',c)
y_label_str='Same for all'

for i=1:6
   hs(i)=subplot(3,2,i);
   plot(a(i,:))
   xlabel(x_label_str)
   ylabel(y_label_str)
   grid on
end

Figure 1: Different xlabel, ylabel for each subplot

enter image description here

Figure 2: The same xlabel, ylabel for each subplot

enter image description here

Hope this helps.

0
Liang Xiao On