Problems saving figure in Matlab with right proportions in pdf file - matlab

I have a figure with 2x3 subplots in Matlab where each subplot contains 2 histograms. I typically save Matlab figures in eps but because doing so removes the transparency between the histograms in each subplot, I resorted to saving as pdf.
Currently, this is how I'm saving the file:
figure;
set(gcf,'Position',[100 100 1400 500])
set(gcf,'PaperPositionMode','auto')
print(gcf, 'filename.pdf', '-dpdf','-r0');
However, it produces a pdf file in portrait layout which means some subplots get cut out.
Now, I've been scouring for answers online and the recommended approach to fix my problem is given in this link.
Following the approach, I don't have any subplots cut out but the problem is that this forces the figure to fill-in the space of my pdf. In otherwords, my histograms are stretched out to fill the space of the pdf file in landscape format. I'd simply prefer a pdf file that has exactly the same proportions as my figure size above which is set(gcf,'Position',[100 100 1400 500]). This is how it works with eps so I'd like to have the same behavior with pdf.
Can anyone help me to fix it?

To make sure the output is landscape:
set(gcf,'PaperOrientation','landscape')
Then use the "bestfit" option. That will scale it as large as possible but maintain the aspect ratio.
print(gcf, 'filename.pdf', '-dpdf','-r0','-bestfit')
There some more good info on Matlab's website

MATLAB’s PDF output is always on a full A4 or Letter-sized page by default. With 'PaperPositionMode' set to 'auto', this does not change. For other output file formats (e.g. EPS) that setting causes the page size to be adjusted to the figure size. Not so for PDF. You need to manually set the 'PaperPosition' and 'PageSize' properties.
This File Exchange submission handles this for you (I’m the author).

Related

Matlab, high quality plot, two legends

I would like to produce a plot with two y-axis and two legends, looking something like this:
I have modified a code I found online to produce a high-quality plot to use in reports/papers. I was wondering how you add a second y-axis in such a code? I have attached the matrix and code to produce the high-quality plot: https://drive.google.com/file/d/1aKZLFeoO1wmQ1P2tEiiucvOFI7PehkGL/view?usp=sharing
https://drive.google.com/file/d/1aKZLFeoO1wmQ1P2tEiiucvOFI7PehkGL/view?usp=sharing
NOTE: This is basically a comment, however, it grew too long, and I felt it was too important not to mention properly.
Reporting plots from Matlab should always, unless you have some very good excuse, be done using vector graphics, i.e. pdf, ps, eps or similar format. The reason for this is the quality, e.g. here I have taken your high-quality and the similar pdf-version and zoomed in.
The png version has artifacts. The reason for this is that the png (similar for jpg and more) is that the picture is saved using pixels, thus when you zoom the quality deteriorate.
The pdf version, which is made with vector graphics, save the vectors, thus when I zoom the pdf viewer can regenerate the pixels and maintain the same quality. As an added bonus, the vector-graphic version is typically smaller in size.
This is made in Matlab using
saveas(gcf,'myfigure.pdf')
Use yyaxis to add another plot with an axis. Take a look at the following modified portion of your code.
yyaxis left
plot(N(:,1),N(:,3)/(27.5*2),'b-','DisplayName','Location','LineWidth',lw); %<- Specify plot properites
yyaxis right
plot(N(:,1),N(:,4)/(27.5*2),'r-', 'DisplayName','NorthEast','LineWidth',lw); %<- Specify plot properites
legend('Location', 'NorthEast');

Exporting and printing matlab figure [duplicate]

This question already has answers here:
Saving MATLAB figures as PDF with quality 300 DPI, centered
(2 answers)
Closed 2 years ago.
I have a Matlab figure. I need to use it as a picture so I can insert it in Word, then save that new Word document as a PDF file and then print that PDF file. I have tried saving Matlab figure as .JPG and . PNG file but the picture gets "smaller" when inserted in Word and converted to PDF and when printed, you can hardly distinguish anything. What can I do so that the quality of the figure dosen't change?
You have a couple of options here.
Specify the Resolution
When saving the figure, by default 72 dpi is used (your screen resolution) which may causeyour images to appear small when being inserted into a Word document. Rather than using saveas, you can use print to specify the resolution of the resulting image. For a PNG
print(hfig, 'filename.png', '-dpng', '-r300') % Resolution = 300 DPI
Note that if you're using print, you will also need to specify a few other properties of the figure to get it to look similar to the on-screen appearance.
set(hfig, 'Units', 'inches');
pos = get(hfig, 'Position');
set(hfig, 'PaperPositionMode', 'manual', ...
'PaperPosition', [0 0 pos(3:4)], ...
'InvertHardCopy', 'off');
Use an EPS
If you're ultimately exporting to a PDF and your image is line art, consider exporting to an EPS (a vector-graphic). Again, this can be done using print.
print(hfig, 'filename.eps', '-depsc2')
Use export_fig
The FEX submission export_fig is a widely-recommended utility for creating figures from your MATLAB figures in a way that preserves the way that they appear within MATLAB.
You don't need to save it as a file, just copy it to the clipboard and then paste it, it will be copied as a metafile (vector graphics) that looks good when resized. It is best to resize by dragging the corners to maintain the original aspect ratio.
After you make a figure, select from the figure menu: Edit / Copy Figure and then paste into Word or PowerPoint. You can change some of the options for copying by selecting Edit / Copy Options... from the figure menu

Saving Figure as High Resolution or Lossless Image that can be Zoomed in without Pixelation

I have a big plot in MATLAB (4095 points total) and I want to export this figure as a high res image which can be zoomed in just like the original figure can be zoomed in. Below I attached two images, one is full size plot and the second one was exported separately by zooming in the figure and then exporting. 1st image gets pixelated (obviously) when I zoom in. So my question is if it is possible to export the figure as an image (any format but .fig) that can be zoomed in for more granular detail.
You need to save the figure using a vector format, such as pdf, ps or eps.
For example: try
plot(sin(0:.001:2*pi)) %// example graph
The resulting figure is:
Then print to pdf:
print -dpdf example %// Or change -dpdf to -deps, -depsc, -dps, -dpsc
Now open the generated file, example.pdf. You can zoom on it and you won't see it pixelated. Here's an example of the top of the sinusoid at 6400% zoom.

When saving a figure as eps file, Matlab cuts off colormap labels

I have a figure generated using contourf with a colorbar. Most of my plots are fine, but when the values on the colorbar are of the order 10^{-3}, either the numbers 0.005 etc are written by the colorbar, or x10^{-3} is written at the top.
In both cases, part of the label gets cut off - either the 3 in x10^{-3} or half of the 5 in 0.005.
I can fix this using
set(gca, 'ActivePositionProperty', 'OuterPosition')
for the figure onscreen, but I need to save it in eps format. When I do this, the 3 (or 5) is cut off again!
I can also fix this if I manually pull the bottom right corner of the figure window to make it larger. But this changes the sizes of the axis labels etc in comparison to the plot itself so that they're different to all my other figures, i.e. the figures that I don't resize.
Any suggestions?
Matlab uses two sizes for figures: screen size (Position figure property) and the PaperSize. The former is used for displaying on screen, and the latter for printing or exporting to image formats other than .fig. I suspect this is the source of your problem.
Here is what you can try:
size = get(gcf,'Position');
size = size(3:4); % the last two elements are width and height of the figure
set(gcf,'PaperUnit','points'); % unit for the property PaperSize
set(gcf,'PaperSize',size);
This sets the size of the "paper" to export to .eps to the size of the figure displayed on screen.
If this doesn't work, you can try to play a bit with PaperSize or other "paper" related properties. The Figure Properties documentation page gives more info about properties.
Hope this helps!
The former suggestion is partly correct. Here is what i did:
set both, figure and paper units, to the same measure (figure has pixels, not points!)
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
do the same as suggested before:
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
the thing now is, that it might be shifted off the paper, as in my case, so put it back on
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
I am not sure about the offset of [0,0], but what is a single point cut off :)
Try this to save your file to filename.eps:
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
print(gcf,'filename','-depsc','-loose'); % Save figure as .eps file

how to make an image large enough to avoid tick label overlapping?

Assume that the data X has size 1000 *1000. X is displayed using the command:
imagesc(X);
and all the rows are labeld using:
set(gca, 'YTickLabel', somelabels);
Although the data X are properly polotted and the Ytick labels are also shown, the labels are highly overlapped because of the large number of rows. Is there any way to solve the problem? Any help will be highly appreciated.
Edit 1
I realize my question was not stated well to represent my problem. I am going to wrap up my understanding based on the answers and re-ask a question:
To show as many rows/labels in a Figure Window, the following helps:
set(gca,'FontSize',6),
or, alternate the distance (suggested by yuk),
or, set(gca,'YTick',1:10:1000,'YTickLabel',somelabels(1:10:1000));
The code
set(gca,'Units','pixels','Position',[20 20 10000 10000]);
will display a zoomed-in image by default. But if the zoomed-in image is too large to fit in the Figure Window, only part of the image will be displayed. However, neither zoom out nor the pan tool can reach to the rest part of that image.
The default behavior of the code
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
displays the whole image fitting to the Figure Window with overlapping labels. Nevertheless, it does allow one to zoom into part of the image and to see the un-overlapped labels.
If I save the image into a pdf file:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
saveas(gcf, 'fig.pdf');
Then the saved pdf is only the image fit to the Figure Window with overlapping labels. However, unlike zoom in within Matlab figure window, zoom in within a pdf reader won't change the relative position/distance of labels. As a result, the zoomed-in image in pdf is still label-overlaped.
So my question is:
How to save the image into a pdf file or png such that it has a similar behavior as of point 3 above when opened in Adobe reader, rather than that of point 4?
You can also play with axes label font to make it smaller.
set(gca,'FontSize',6)
See also other axes properties to change font - FontName, FontWidth, FontUnits, etc.
Another solution: If your labels are short, you can alternate there distance from the axes, so the labels will not overlap. Check this example:
lbl = cellstr(reshape(sprintf('%3d',1:100),3,100)');
lbl(1:2:100) = strcat(lbl(1:2:100),{' '});
imagesc(rand(100))
set(gca,'ytick',1:100)
set(gca,'yticklabel',lbl)
Part of the resulted image:
UPDATE
To answer your updated question.
PDF document can contain only static images. Once you saved the figure to PDF (or any other graphic file), you cannot zoom in/out as with MATLAB figure tools.
You can zoom first on the MATLAB figure, then save PDF file. In this case the figure will be saved as is. But this way assumes user interactivity with the figure.
If you know your region of interest in advance, you can set axes limits with XLim/YLim properties, then save the figure.
Example:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
set(gca, 'XLim',[1 20], 'YLim', [20 40])
saveas(gcf, 'fig.pdf');
By the way, you can also save figure to file with PRINT function. More flexible. SAVEAS is just wrapper around it.
print('-dpdf','fig.pdf')
Another option is to rotate the tick labels which is discussed in this technical solution. You can find a number of easy-to-use implementations on the MATLAB File Exchange.