2

I am producing some figures in MATLAB and try to insert them in LaTeX. However, when I do so, they usually don't have the same size (although I am using the same setup to produce them).

For example:

enter image description here

The MATLAB code I am currently using is this one

lsize = 16; % Label fontsize
nsize = 16; % Axis fontsize

q=randn(100,1000);

a1=linspace(1,1000,1000);
b1=linspace(2,2000,1000);


figure (1)

histogram(q)

xlabel('Time [sec]','Fontsize', lsize)
ylabel('W_{kin} [keV]','Fontsize', lsize)

set(gca, 'Fontsize', nsize)
set(gcf,'paperpositionmode','auto');
set(gcf,'windowstyle','normal');
set(gca,'LooseInset',max(get(gca,'TightInset'), 0.02))
set(gca,'fontweight','normal')


opts.Colors     = get(groot,'defaultAxesColorOrder');
opts.saveFolder = 'img/';
opts.width      = 12;
opts.height     = 10;
opts.fontType   = 'Times';

saveas(gcf,'f1.png')

figure(2)

loglog(a1,b1)
xlabel('time [sec]','Fontsize', lsize)
ylabel('Speed [m/sec]','Fontsize', lsize)

set(gca, 'Fontsize', nsize)
set(gcf,'paperpositionmode','auto');
set(gcf,'windowstyle','normal');
set(gca,'LooseInset',max(get(gca,'TightInset'), 0.02))
set(gca,'fontweight','normal')


opts.Colors     = get(groot,'defaultAxesColorOrder');
opts.saveFolder = 'img/';
opts.width      = 12;
opts.height     = 10;
opts.fontType   = 'Times';

saveas(gcf,'f2.png')

The latex code I am using is:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}   % needed for figures

\begin{document}

\begin{figure}[!ht]
     \begin{center}

         \includegraphics[width=0.3\textwidth]{f2.png}\\ 

         \includegraphics[width=0.3\textwidth]{f1.png}


     \caption {A caption}\label{A_label}
     \end{center}
     \end{figure}

\end{document}

Am I doing something wrong?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 1
    Unrelated side-note: `get/set` has been superseded with the graphics engine overhaul by using handles, e.g. `fig = figure()`, `line_handle = plot()` etc. Makes for less messy code, as you can then do `fig.windowstyle = 'normal'`. For subplots you might also want to take a peek at [`tiledlayout`](https://mathworks.com/help/matlab/ref/tiledlayout.html), which more or less supersedes `subplot`, and has a lot more options for design control. – Adriaan May 27 '20 at 10:11
  • 2
    For use in LaTeX documents I'd suggest using a vector graphics file, such as eps or pdf. For high-level control of everything figure-related on MATLAB's side, I can recommend taking a look at [`export_fig()`](https://mathworks.com/matlabcentral/fileexchange/23629-export_fig) on the File Exchange. – Adriaan May 27 '20 at 11:18
  • @Adriaan I have seen this file before, but I was not able to use it? For my purposes, could you elaborate a little more on which of the included functions is useful? –  May 27 '20 at 11:37
  • It's a toolbox, more or less. `export_fig.m` is the main function. That has enough documentation in its help and on the FEX. – Adriaan May 27 '20 at 11:46
  • 1
    Unrelated to your problem, but I would suggest to not use the `center` environment inside a figure. Instead one can use `\centering`. This will avoid the additional vertical space from center – samcarter_is_at_topanswers.xyz May 27 '20 at 18:48

1 Answers1

1

I had a similar issue when trying to plot massive data in LaTeX (which it is not made for) so I wanted to draw the figures in MATLAB and arrange them (and the axes) in LaTeX. So I printed them as PDFs.

The trick to always meet the exact figure sizes is to make the axes fill the whole figure with set(gca,'position',[0 0 1 1]). You will need to draw the axes, ticks, and labels in LaTeX (remember to use the option axis on top in pgfplots there).

function printFig2PDF(fh,FigName,FigWidth,FigHeight)
%% export MATLAB-figure as PDF

Format = 'pdf';

% check if input name has an extension
lst = strsplit(FigName,'.');
if ~strcmpi(lst{end},Format)
    % append format
    FigName = strcat(FigName,'.',lower(Format));
end

%% adjust figure
if ~isempty(fh.ax.Legend)
    fh.ax.Legend.Visible = 'off';
end
fh.ax.Box = 'off';
set(    fh.ax, 'YTickLabel',{},'XTickLabel',{});
set(    fh.ax, 'yColor','none','xColor','none');


set(fh.ax, 'Position',[0 0 1 1])

set(fh.fig, 'PaperUnits','centimeters',...
        'PaperPosition',[0 0 FigWidth FigHeight],...
        'PaperSize',[FigWidth FigHeight]);

% save as PDF
print(fh.fig,FigName,'-dpdf')
% close figure handle
close(fh.fig)
end

Note that I assume that the first input (fh) is a struct with the fields fig which as a figure handle and ax which contains an axes handle (which is how I store those handles if I have multiple figures and subplots). If you want to plot the current figure with only one axes, you can create it with

fh = struct('fig',gcf, 'ax',gca);
max
  • 3,915
  • 2
  • 9
  • 25
  • Thank you very much for taking the time to reply! Have a great day! –  May 27 '20 at 14:48
  • Sorry to bother you again. I tried your code and works great. However, I don't seem to get the axis ticks (which i difficult to draw on latex). is there a way to prevent this? Thank you again! –  May 27 '20 at 15:56
  • I disabled them on purpose (the line where the `yColor` and `xColor` was `set`), because it looks stupid if LaTeX draws them again on top of the figure... It shouldn't be too hard to draw them in `pgfplots`. I think it was [this](https://tex.stackexchange.com/questions/536656/draw-invisible-axes-with-visible-labels) question – max May 28 '20 at 05:20