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

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');

Related

Copy figure in Matlab

I am asking for a solution to the blurred image I get when I use copy figure option in Matlab. For example, when I plot 3d figure in matlab I get the following image (It is the result of printscreen!)..
However, when I use the option copy figure I get a blurred image as the following image
.
How can I avoid this as I need to get high resolution image using copy figure option. Thank you in advance for any help you may lend.
By default, the figure is copied as an Enhanced Metafile (a color graphics format) which works for basic plots such as bar plots, line plots, and other 2D plots but may yield undesirable results for more complex plots as in your case. This is because the rendering of the Metafile content is controlled my Microsoft Word and it may render things differently than MATLAB.
If you need a high resolution image, I would recommend using the print command where you can specify the desired resolution (using the -r option). Then you can import the resulting image into Word
print(gcf, 'myfile.png', '-dpng', '-r300')
Alternately, you can use export_fig from the File Exchange which better preserves the appearance
Another option would be to change the format used by Copy Figure to tell it to use a bitmap instead
Or you can call Copy Figure programmatically and specify a different format (either a bitmap or PDF)
print(gcf, '-clipboard', '-dpdf')

exporting svg image from matlab surface plot

I need some to produce some publication-quality figures. I first export the figures from matlab in .svg format, and then I do some post-processing in inkscape. I am no problem with figures generated using plot or scatter, but when I export figures generated using surf (in view(2)), I run into problems. If I use plot or scatter, I am able to ungroup and process various parts like the title, axes, scattered points, lines, etc. in inkscape. For surf, however, matlab just exports one single figures with all various parts grouped into one single unit. I can't separate individual part, and when I zoom very close I can actually see the bitmap resolution for the axes and titles (if I use plot, the titles and axes have 'infinite' resolution when I zoom very close). I am fine with the surface plot having finite resolution, but I need to at least be able to process the axes and titles (which I currently cannot do). What should I do so that I can 'separate' the title and axes from the main plot, just like figures generated from plot and scatter?
I stumbled across this question, since I encountered the same problem.
As mentioned by #vindarmagnus, it is possible to use tikz and get rather nice results. However, tikz experiences problems with large data sets in my experience as present when using surf etc..
Solution, that worked for me:
Change the renderer to painters and the exported .svg file will retain its vectorgraphic properties when opened e.g. in inkscape:
figure('Renderer','Painters');
I used to use Inkscape for my scientific publications as well, but I found that a lot of the time you can get better results with pgfplots in latex, together with the matlab2tikz matlabscript. There’s a ton of resources about this online, but here’s how my workflow would look adopted to your surf situation. I have macOSX with latex, matlab and matlab2tikz installed. Will work with little to no modifications on linux.
In Matlab:
surf(peaks(25))
matlab2tikz('plot.tikz’)
Then I have the following bash-script (just a script in the same folder as the image, which is executed by mere double-click). (Needs to be chmod-ed as an executable for that).
#!/bin/bash
cd ~/Desktop
rm *.eps
cat > plot.tex << EOF
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{max space between ticks=50}
\pgfplotsset{scaled ticks = false}
\pgfplotsset{compat=1.6}
\pgfplotsset{xticklabel style={/pgf/number format/fixed}}
\pgfplotsset{yticklabel style={/pgf/number format/fixed}}
\begin{document}
\input{plot.tikz}
\end{document}
EOF
pdflatex plot.tex
pdf2ps plot.pdf
ps2eps plot.ps
Note that the row cd ~/Desktop above should be changed as to reflect which folder the script is supposed to be run from (a bit crappy, but needed since Finder doesn’t properly pass along the folder from a program is executed, afaik).
This yields high-quality images in eps or pdf or what you like, with a ton of settings for axes and ticks etc. And it all uses native latex fonts.
Edit:
Recently I’ve begun to use patch() in matlab and then export it to tikz in the same manner as above, with great results. That’s another suggestion!
You can use also:
set(gcf,'Renderer','Painters')

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)

How to export non-blurry eps images?

I'm exporting an image in Matlab using the eps format, but it smooths the image. Matlab does not blur the image using other formats such as png. I would like to know how to export a non-blurry image with eps format. Here is the resulting image using png:
And here is the resulting image using eps:
UPDATE:
The problem is reproducible on a Mac, and the issue is with the eps renderer rather than MATLAB. For e.g., saving imagesc(rand(20)) and viewing with Preview and GSview results in the following:
Preview screenshot
GSview screenshot
Clearly, the information is not lost. It is just not interpreted/read correctly by some EPS viewers. The solution is simple: use GSview to view your eps images. You can download it from here
On Macs especially, if your end application is latex/pdflatex, you will have to explicitly set it to use GS/GSview, because otherwise, it will default to the Quartz engine, which is baked into the OS.
PREVIOUS ANSWER:
I am unable to reproduce the behavior your described. Here is the code I used, tested using R2010b on WinXP 32-bit:
M = fspecial('gaussian',[20 20],5);
imagesc(M)
print('-dpng','a.png')
print('-depsc2','b.eps')
a.png
b.eps
Perhaps this is an issue with your EPS viewer...
not sure why it works but you can try doing the following:
eps2eps oldfile newfile
does the trick for me (on a mac os)
At first I thought you were doing something incorrectly, but then I remembered that this was an issue that was bothering the hell out of me a year or so ago. I couldn't come up with a way to "fix" this behaviour and from what I've researched, this is most likely a bug and several others have had this problem too and there is no known solution. Of course, I could be wrong about the last part and there might be solutions out there that have come out since I looked for them.
Any way, my workaround this problem was to use pcolor with shading flat instead of imagesc. When you export this to an eps format it preserves the image correctly. Example:
pcolor(rand(20));
shading flat
print('-depsc','figure.eps')
NOTE: You might see the appearance of thin, faint white lines along the anti-diagonals of each little square (depends on the OS & viewer). These are the edges of the graphics primitives that are used to render the image. However, this is not a flaw in MATLAB's export, but rather a fault in rendering in your EPS/PDF viewer. For e.g., with the default settings in Preview on my mac, these lines show up, whereas with the default in Adobe Reader 9.4, they don't appear.
If anyone is still interested in a workaround: Open the .eps-file with text editor and search for "interpolate". You'll probably find "/Interpolate true def" two or three times. Replace "true" with "false" and be happy :)
A note regarding Yoda's answer: in Preview in Mac OS X, you can make the thin white diagonal lines across each of the squares disappear by unchecking "Anti-alias text and screen art". Of course, the downside is that then any text (e.g. figure axes, etc) is not anti-aliased. Unfortunately, unchecking that has no effect on blurriness if you're using imagesc.
Another note is that if you use preview to make a pdf from your eps, the resulting pdf still displays correctly (non-blurry) when you open it in Acrobat.
I've been long struggling with this problem as well. So far, GSView is the only viewer I've found that displays the eps figures produced by Matlab (R2015b) correctly. eps2eps did not work for me (psutils 1.23).
The following eventually worked for me:
Export the figure to pdf, following the instructions here
pdf2ps file.pdf file.eps
I just wrote this simple drop-in replacement for imagesc. It doesn't support all but the most basic features, but I still hope it helps.
function h = imagesc4pdf(C)
[ny nx] = size(C);
px = bsxfun(#plus, [-0.5; 0.5; 0.5; -0.5], reshape(1:nx, [1 1 nx]));
py = bsxfun(#plus, [-0.5; -0.5; 0.5; 0.5], 1:ny);
n = numel(C);
px = reshape(repmat(px, [1 ny 1]), 4, n);
py = reshape(repmat(py, [1 1 nx]), 4, n);
h = patch(px, py, reshape(C,1,n), 'linestyle', 'none');
xlim([.5 nx+.5]);
ylim([.5 ny+.5]);
set(gca, 'ydir', 'reverse');
Apply opengl renderer to the figure
figure(gcf);
set(gcf,'renderer','opengl');
The blurring actually depends on the rendering software your viewer application or printer uses. To get good results all the time, make each pixel in your image an 8x8 block of pixels of the same color, i.e. resize the image like this:
im2 = imresize(im1, 8, 'nearest');
The blurring then only affects the pixels at the edge of each block. 8x8 blocks are best as they compress without nasty artifacts using DCT compression (sometimes used in eps files).
This page helped me a lot: http://tech.mof-mof.co.jp/blog/machine-learning-octave.html (written in Japanese, please use google translate for it)
And this is also helpful: Octave-Gnuplot-AquaTerm error: set terminal aqua enhanced title "Figure 1"...unknown terminal type"
I also answered at https://www.coursera.org/learn/machine-learning/discussions/weeks/2/threads/Dh-aRfqSEeaHSQ6l4xnh6g.
I reinstalled gnuplot like this:
$ brew cask install xquartz
$ brew cask install aquaterm
$ brew uninstall gnuplot
$ brew install gnuplot --with-aquaterm --with-x11 --with-qt # you can show other options by `$ brew options gnuplot`
You may edit ~/.octaverc like this:
setenv("GNUTERM", "qt")
and in octave window, after typing "system gnuplot", then
set pm3d interpolate 2, 2
After saving the file, open octave-cli.app, and type
imagesc(magic(3)), colorbar
I got this.

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.