Difference between print/saveas and export - matlab

I'm doing some plots in Matlab, but when exporting to pdf I'm not getting the same results I see on my screen. In particular, I'm trying to put white edges to the legend.
leg1 = legend(names);
set(leg1,'EdgeColor',[1 1 1]);
When using "File -> Save As -> Out.pdf" the edges are white, but when I use saveas(gca,'Out.pdf') or print -dpdf Out.pdf the edges are black. What is Matlab doing when I use the export function? How can I have the same results from the command line?
Edit
Just to be clear, this is an example code:
plot(rand(10,1))
leg1 = legend('Data');
set(leg1,'EdgeColor',[1 1 1]);
print -dpdf Out.pdf
The pdf file shows this:
Which clearly is not the intended figure, and its different from the one showed by Matlab. When I use the "File -> Save as" option, the edge of the label is displayed correctly.

When saving from the "File -> Save As " it runs an mfile filemenufcn.
You can call it diretly from the commandline:
filemenufcn ( figHandle, 'FileSaveAs' )
Its a shame Mathworks don't allow you to pass in a filename to save directly...
You can investigate that function to see what the function is doing to the figure before its being saved.
FYI: In the latest Matlab (R2015a) the final code that does the actual saving to pdf is hgexport. (Which is a p-code file but it does have some basic help) You could directly invoke that at the commandline.
You should also look at export_fig which is an excellent tool for exporting graphics to file.

I am afraid that the other answer does not really answer the question. This is how you "print" white line/text to a file: run
set(gcf, 'InvertHardCopy', 'off');
before using the print command.
However, for your specific case, since you are just trying to hide the box borders, the better way to do it is
legend boxoff
or
legend('boxoff')
Source: https://www.mathworks.com/matlabcentral/answers/102484-why-does-my-white-text-become-black-in-my-figure-when-printing-to-an-emf-file-in-matlab-7-5-r2007b

Related

Saving figure to pdf prints # instead of tabs in titles

if I create a plot with some tabs in the titles and try saving that to a local pdf file (via print function), I get some hashtags instead of tabs in the pdf. This does not occur in the visible figure.
For example, I plotted the residuals of an approximant to the runge function on a grid:
plot(g, f(g) - runge(g));
title(sprintf('residuals,\t max_x(s-f) = %.3f', max(f(g)-runge(g))));
Then after some axes manipulation (grid, boxes, etc..) I execute
h = gcf;
set(h,'Units','Inches');
pos = get(h,'Position');
set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])
print(h,'data/runge_example.pdf','-dpdf','-r200')
close(h)
Is somebody aware of that behaviour or better able to found that as already solved than I am?
EDIT: Same behaviour with saveas and saving to eps. This does not happen with \n
EDIT2: I'm using Matlab Version R2017b (9.3.0.7...)
So, after a long discussion we figured out that we have no idea of how to use tabs in matlab titles in combination with latex mode.
To clarify: use math environments and escape tex directives, otherwise it will throw an error.
so
sprintf('residuals,\t $max_x(\\vert s-f\\vert) = %.3f$', max(f(g)-runge(g))));
will give you a nice string:
residuals, $max_x(\vert s-f\vert) = 0.264$
The problem is, that it really is a tab. And the matlab latex interpreter (don't know which one that uses, the system or an own) crashes on that. I copy-pasted that to a tex document and pdflatex ran fine on it (but not showing that much space unfortunately).
So, I came up with the following fix:
use the latex directive \quad or \qquad:
title(sprintf('residuals,\\quad $max_x(\\vert s-f\\vert) = %.3f$', max(abs(f(g)-runge(g)))));
This will give you more space than a normal space.
EDIT: For this to work you need the interpreter of matlab to be set to "latex" instead of the default "tex". Do this by changing the title to
title(title_string, 'Interpreter', 'latex')
or by setting (globally for that script)
set(groot, 'defaultTextInterpreter', 'latex')

Matlab figure saved as .eps appears in 'horizontal sections' when opened in Adobe Illustrator

I normally save my matlab figures as .eps and then make them better looking using Adobe Illustrator. This works for most figures but not all.
For example I plotted my data using the violin.m function from file exchange. When I save it as .eps and open it in Illustrator, I don't get an editable figure as I usually do. Instead, My figure appears chopped in horizontal sections, and all I can do is delete them (like in the figure below).
Is there anything I can do in either matlab or Illustrator to be able to edit the figure?
I don't need an .eps file, I just need to be able to edit it.
EDITS:
I tried #MattSchmatt's suggestion of using the print2eps function but I had the same problem.
Saving as .pdf doesn't solve the problem, because the image I get is not editable in Illustrator (plus, I also get the horizontal 'chunks').
A minimal, complete and verifiable example requires matlab, the violin function linked above and illustrator. But if it helps, here's the matlab code to produce a similar figure. I save by clicking on Figure -> save as. (But as I said above I tried the print2eps function and that was the same).
X = rand(100,6);
figure; violin(X)
I tried the following, didn't work either.
set(gcf, 'Renderer', 'painters')
As the author of the question suggests, I also wasn't able to export an editable (vectorized) .eps file into Illustrator. However, exporting it as .pdf does the trick. The 'fill' for the violin plots is weird, though, and has horizontal sections (perhaps something to do with the way the density estimate is being plotted?) all over. I was able to fix this and make the plots normal (with solid filled shades): select all the horizontal sections/chunks using the magic wand tool, and then increase opacity to 100% (it is set to 50 based on the exported file). Once all the required edits are made, export the file as .tiff and it seems to look fine. Hope this replicates, and thus helps! (my MATLAB version is 2016, and Illustrator version is the CS5)

Exporting figures as vector graphics in .pdf-format using HG2-Update and 'painters' renderer is not working properly

I'm using the still undocumented HG2-Update to create my MATLAB plots, because they just look that much nicer.
(Source: Yair Altman)
Actually, using the current version Release 2013b it works quite nicely and there are not much issues. Except one wants to export the figures as vector graphics (renderer: '-painters'), especially as pdf.
I use the commands:
saveas(gcf,'test.pdf','pdf')
or
print(gcf,'test.pdf','-dpdf')
There are rendering issues, the print does not contain the whole figure and some parts are cropped or non-default fonts are not recognized.
But I'd really like to stay with HG2 and I'd still like to use vector graphics. Is there any solution or workaround?
Exporting vector graphics using the yet not official HG2-Update is quite an issue. The .pdf-export is still totally screwed up.
What is working fine is the .svg-export, apart from that the boundary box is not set properly.
The long workaround would be:
Save the plot with '-dsvg' (print-command) or 'svg' (saveas-command) as vector graphic, open the file in the open source application Inkscape and save again as .pdf with the Export area is drawing checkmark set.
Quite complicated, so I found a way to do it via command-line directly from Matlab (Inkscape still required!):
filename = 'test';
inkscapepath = '"C:\Program Files (x86)\Inkscape\inkscape.exe"';
%// save as .svg
saveas(gcf,filename,'svg')
%// open and save with "export-area-drawing" set via command line
system( [inkscapepath ' ' filename ...
'.svg --export-area-drawing --export-pdf=' filename '.pdf'])
It takes some time, but works without any known issues for now.
Additionally delete the svg-File afterwards:
delete([filename '.svg'])
I had the same problem and used the workaround from thewaywewalk. Now I discovered the MATLAB function "hgexport" works under HG2 (in R2014a).
An issue still was the paper size. I want to use the same size for all graphs with as little white frame as possible. Here you have to set two sizes:
The papersize is set with set(gcf,'PaperSize',[width height]) and the size of your chart is set through export styles. These are set in "Export Setup" or command line:
exp_style=hgexport('readstyle','default');
exp_style.Width = 'width';
exp_style.Height = 'height';
exp_style.Renderer = 'painters';
Now you can export your pdf:
hgexport(gcf,'pdfname',exp_style,'Format','pdf');
PS: In HG2 you may also use Latex for tick labels:
set(gca,'TickLabelInterpreter','latex');

MATLAB: print a figure to pdf as the figure shown in the MATLAB

I am trying to export (save as, print) a figure into .pdf format. However, no matter how I configure the setting, there are large margins around the figure.
When I export the figure into .eps format, there is no such problem --- i.e. the figure just looks like it is displayed in the MATLAB.
How could I export the figure into .pdf format, which looks the same as it is shown in the MATLAB?
You can automate the process above by adding the following lines of code immediately after the plot command.
set(gcf,'Units','inches');
screenposition = get(gcf,'Position');
set(gcf,...
'PaperPosition',[0 0 screenposition(3:4)],...
'PaperSize',[screenposition(3:4)]);
print -dpdf -painters epsFig
The first two lines measure the size of your figure (in inches). The next line configures the print paper size to fit the figure size. The last line uses the print command and exports a vector pdf document as the output.
You can try the following:
1) After you plot the figure in MATLAB, go to 'File->Export Setup', and input the size of the output you want. For example, Width: 6 inches, Height: 5 inches. Then click 'Apply to Figure' button.
2) Don't close the 'Export Setup' window. Go to 'File->Print Preview->Paper', input the same size in the Width and Height options.
3) Don't close the 'Print Preview' window. Go back to the 'Export Setup' window, and click 'Export', then select pdf format and save it.
4) Check the output PDF file, you'll see it is perfect.
I found the solution in blog post Export figure to PDF in MATLAB.
2-lines script, for exporting to PDF in landscape A4 (assuming your plot is the "current figure"):
%-------------------------------------------------------------------
% resize paper as a landscape-A4 and reposition figure accordingly
set( gcf,'PaperSize',[29.7 21.0], 'PaperPosition',[0 0 29.7 21.0])
% export to PDF file 'YourFileName.pdf'
print -dpdf 'YourFileName'
%-------------------------------------------------------------------
Any other tweak : check the Figure properties - simply "get( gcf )" on the command window

How to print figure to clipboard by PRINT function with the quality identical to 'Edit-->Copy Figure' option?

Is there any way to print the figure to the clipboard so that the quality is identical to what the Edit-->Copy Figure option provides?
I used to save the figure to powerpoint file by using saveppt.m obtained from Matlab Central. It worked well until yesterday. I noticed that the stored image quality was somehow degraded. I tried to re-generate some ppt slides with exactly the same script and the same source data, but the new slides are simply of worse quality.
I investigated into this problem a little bit and discovered that when the figure is copied to clipboard by running print -dmeta, the image in the clipboard is already degraded, while if I use the Edit-->Copy Figure option in the figure window, I get the image as clear as the original image in the figure window.
Following is an example for your reference. I copied the image from a figure to the clipboard by two different methods, and paste it to Microsoft Paint program, and cut a piece of it to show below:
The image using print -dmeta:
The image using Edit-->Copy Figure:
If you compare the Xtick label '50', you may see that the image from Edit-->Copy Figure is smoother.
At the beginning I thought it was a problem of the resolution, but setting -rN to change the resolution does not seem to resolve my problem, at least not for N<=300.
Thank you for your help.
The short answer... Use the same function invoked in the callback for that menu item:
editmenufcn(gcf,'EditCopyFigure');
The longer answer... How exactly did I find this? You can look at my previous answer to a related question about reproducing what is done by a File menu option. The concept is the same, just for a different figure menu. For example, this will find the callback you want for the currently active figure window:
>> hCopyFigure = findall(gcf,'Label','Copy &Figure'); %# Handle for the "Copy
%# Figure" menu item
>> get(hCopyFigure,'Callback') %# Callback invoked when that item is selected
ans =
editmenufcn(gcbf,'EditCopyFigure')
The function EDITMENUFCN is another one of those sparsely documented functions, but looking through the code (by typing edit editmenufcn.m) shows that it either invokes Java (if you're on a Mac) or the undocumented function UIMENUFCN.
I think I found the answer myself. Using print -dmeta -painters to specify the renderer resolves my problem.
In File-->Preference-->Figure Copy Template-->Copy Option I noticed there are 3 options:
Metafile
Preserve information
Bitmap
I found that if I select 1, the Edit-->Copy Figure outputs the same image as print -dmeta. So I kind of confirmed the information I need is in the Preserve information option. A quick google search led me to the discussion about the potential difference of the applied renderer, and eventually I confirmed that using painters will print the image to the clipboard in the way I wanted.
The image in the question seems to be generated by the renderer zbuffer and painters, respectively. I still don't know why the default renderer of paint -dmeta changes, though.