Search code examples
matlabmatlab-figure

Multiple Plot Matlab including image


I use the tiledlayout(2,2) command to create a plot in Matlab. The first three title fields filled with normal plots. The fourth and last field is a field with an image. I used the commands IMG = 'mypic.tif'and imshow(IMG).I wonder why I can not change the size of my image. Is this not possible with the tiledlayoutcommand? I have looked up the documentary for tiledlayout and imshow(), but found nothing which helps me.


Solution

  • It indeed seems as if this is not possible using the tiledlayout functionality. However, it is possible using the subplot functionality. Below, I will give an example how this works.

    Consider the following script:

    % Generate some dummy data for the four plots
    x = linspace(0, 2*pi, 25);
    y = sin(x);
    
    % Load sample image
    image = imread('ngc6543a.jpg');
    
    % Generate the figure
    fig = figure(1);
    
    % The three subplots
    for i = 1:3
        subplot(2,2,i);
        plot(x, y);
    end
    
    % The image
    subplot(2,2,4);
    imshow(image);
    
    % Increase size of the image
    size_factor = 1.4; % 1.0 is original size
    
    im_ax = fig.Children(1);    % axes belonging to image
    dims = im_ax.Position(3:4); % current dimensions
    
    dims_new = size_factor * dims;  % scale old dimensions
    dxdy = (dims_new - dims) / 2;   % offset for left bottom corner of image
    
    im_ax.Position = [im_ax.Position(1:2) - dxdy, dims_new]; % update position
    

    In this script, we start by generating some dummy data for the three 'normal' plots and loading a sample image (this image came with my MATLAB installation). Subsequently, we create a figure. After the figure has been created, I add the three dummy plots to the figure using a for loop and the subplot functionality. Then, we plot the image using imshow in the fourth subplot.

    Now, the interesting part begins. First of all, I define a scale factor for the image (size_factor). Then, I retrieve the axes in which the image is plotted and store it in im_ax. From this axes, I retrieve the last two elements of the Position field and store them in dims. These two elements define the size of the axes. Based on the value of size_factor, I calculate the new size of the axes and store this in dims_new. To ensure that the axes (and thus the image) remains centered, we need to calculate by how much we need to shift the left bottom corner of the axes (whose coordinates are stored in the first two elements of the Position field). This result is stored in dxdy. The last thing we do is simply updating the Position field of the axes in which the image is plotted.

    Now, to show you some results:

    1. size_factor equals 1.0: size_factor equals 1
    2. size_factor equals 1.4: size_factor equals 1.4
    3. size_factor equals 0.55: size_factor equals 0.55