altmany/export_fig

Lines on Patch-Objects after *.EPS/PDF export - e.g. with contourf

phwi opened this issue Β· 74 comments

phwi commented

I know that there are plenty of comments on strange lines appearing in exported matlab output, still I didn't really find out if there is already a solution to my specific problem.

About 3 years ago I exported a MATLAB contourf plot to *.eps with export_fig of ojwoodford. I guess it was MATLAB R2012a or b and the present version of export_fig those days. It worked perfectly and there were no strange atrifacts, whatsorever.
Yesterday I did the same with MATLAB R2014b and the current release of export_fig. Now I have strange artifacts when exporting to *.eps or *.pdf.

See the attached image (left: 3 years ago, right: yesterday - it's a different colormap and a different matrix of data, but this shouldn't be the problem...)
lines_in_contourf

Unfortunately those white lines are really present --> When I import the *.eps e.g. to Corel Technical Designer and further edit the image to do some tweaks for my presentation, these lines remain visible. After doing some editing and exporting from Corel Technical Designer to *.png or *.eps - I have the lines in both output formats...

Is there any solution to this problem?
Is it a bug or a feature?
Why did it work 3 years ago and now it doesn't anymore?

Is it the same issue that was already reported (#28) and ojwoodford responded that it is a bug, which will be fixed in the next MATLAB release: #28 ?? --> Because I just updated to MATLAB R2015a and to the latest export_fig release. The problem got not fixed...
Thanks for your help!

PS: In between I believe it is actually the anti aliasing... in adobe reader I can set a property (2D graphics accelaration) --> if switched on: the lines disappear. If turned off --> the lines reappear. But in most of the other programs (including GS viewer) I didn't manage to get rid of those lines. Actually the lines obstruct further editing in some third party software outside of MATLAB... and I don't get why I did not have those lines when exporting three years ago... I checked my *.eps files from then: no lines at all in none of the figures I exported then (neither in GS viewer nor in third party software...) --> So why do those lines appear now??

@phwi - export_fig uses Matlab's underlying print() function to export the data to EPS/PDF, and as far as I am aware these extra lines are due to an internal Matlab bug in print(), probably due to the new graphics engine (HG2) that was introduced in R2014b.

To verify that this is indeed the problem in your specific case, try using Matlab's print() directly and check whether the lines appear in the output. If you ever find a workaround (possibly involving some print() input parameter), then please report it so that it could be integrated into export_fig.

There is currently no known workaround for vector formats (EPS/PDF), but if you can live with bitmap output then consider using a PNG output format, or use my ScreenCapture utility which takes a bitmap screenshot in a totally different manner, without using Matlab's print() function.

FYI, this export_fig utility is the same as the one you used in 2012 (with natural improvements/fixes) - Oliver Woodford transferred export_fig ownership to me in Jan 2015 for continued maintenance.

phwi commented

Thanks for the response: It's a shame... HG2 improved many graphic related things. Anyway: When I use a cotourf-plot with export_fig in MATLAB 2014a I don't have those tiny annoying lines. I really need the vector output format...

I didn't find out a combination with print(), that works for me... so no matter what I try, when trying to export to any vector format, I will always have those tiny lines. Why can't MATHWORKS just change it in a way that makes contourf-plots look like when exported with HG1?

In fact, it is really about aliasing... e.g. when I look at my figures in adobe reader I don't see those lines. But now I have to find out an option in any program that I plan to use in my work flow, which displays things like adobe reader does... I think this is a poor solution, considering that everything was displayed properly in MATLAB R2014a without having to change any setting in any program.

When I import the *.eps files to Corel, do some further editing and afterwards export it to a bitmap Image like *.png for a presentation, I have to turn off anti aliasing (with all negative side aspects) in order to get rid of the tiny white lines in the *.png (!), otherwise I have those lines in my bitmap-format after exporting... I think I'll have to open a ticket on MATHWORKS. Do you know if there are plans to fix the strange HG2 behaviour regarding those white lines?

Is the thin white line from the bottom right to the top left corner in the below picture caused by the same problem as described above?
The picture is generated with imagesc(...) in Matlab 2014b (OS X Yosemite 10.10.2, export_fig updated from this site earlier today) where the figure is exported to PDF format. If I export to PNG format, the thin white line is not there. I consistently observe this white line whenever I plot data on the entire plane (imagesc(...), surf(...), fill(...)) and export it to PDF format.

image

phwi commented

Hello jakobrdl,

I am not sure if you observe the same problem that I observe: In you're case it looks more like a strange bug to me. The line in your picture goes straight through several different patch objects, while the lines in my picture are always between adjoining patch objects...

@phwi - I discovered that these white line artifacts happen when the painters renderer is used (this was the underlying problem also with issue #39, since painters cannot render transparencies), and painters is the default rendering format for vectorized (EPS/PDF) formats.

In contrast, PNG (and all other bitmap formats) uses -opengl rendering by default, which is probably the reason that the artifacts do not appear there.

So, try to use the -opengl parameter with export_fig and see if it solves the problem for EPS/PDF.

phwi commented

@altmany - I am sorry, somehow I did not point that out, yet: I know that using -opengl solves the problem. My PNG plots, etc. look fine.

I am bothered about the fact not beeing able to export as a vector format without having bugs and artifacts, etc. - because I really need my exports to be a vector format, for more than one reason:

1.) Further and advanced editing and complex merging of different figures, which is not really possible in MATLAB. In fact I embed different figures for comparison in a more or less complex scetch of my measurement setup to point out how the differences in the setup manipulate the measurement data. So I use a third party program, in which i need the original graphics_data as vectors, because the all over quality etc. is far better for high publications, you can zoom into vector graphics endlessly..., the document size is very low compared to high resolution pixel graphics (in order not to see the pixels...).
Long story short: -opengl is just not an option for me!
Why can't mathworks manage things they already managed 3 or 4 versions before...?

  1. Is there some option to disable transparency with -painters?

@phwi - I can't answer for MathWorks. Hopefully they will fix these bugs someday... All I can do is to workaround the bugs by post-processing the generated EPS file. If you have insight into that and know your way around the Postscript code in the EPS file, then let me know what you discover and maybe I can include such a workaround in export_fig (many other internal Matlab bugs were fixed in this way in export_fig).

Regarding transparency, the painters renderer does not support transparency. In this case it's a known and documented feature of Painters (not a bug). Only OpenGL supports transparency. So whenever you export using -painters you will see the result without transparent patches/annotations (even if they appear transparent in the Matlab figure, which uses OpenGL).

phwi commented

@altmany - I have opened a Mathworks support ticket... maybe there is already a workaround to fix the EPS-files in a post-process, which I can then share here in order to get it included in export_fig like the bug with the linejoins, which messed up the graphs totally that I had been reporting some months ago.

Thanks so far, I'll let you know about the answer of MATHWORKS.

phwi commented

Mathworks information:
[...]
Our development team is aware of that issue and is working on improving the way we export vector graphics. However for now, unfortunately there is no other workaround as changing the rendering in the viewer.
[...]

Anyway, we can't derive if and when Mathworks will succeed in coming up with a solution to the issue described in the topic post. Let's hope that it won't take another two or three release versions, until they come up with a solution.

So far I think that this topic can be closed except for someone objecting a solution altering the *.EPS-output in a post-process that makes those tiny white lines vanish without having to change anti-aliasing settings in the desired third party program or pdf-viewer...

@phwi - I've traced the problem down to the fact that Matlab's print() function exports patches as a combination of filled triangles, and a white line appears where the triangles touch. I uploaded a workaround that converts such dual-triangles into a single filled rectangle.

I was careful to only modify regexps that exactly match specific triangle patterns - it's better to not correct some white-line artifacts than to change the geometry of a patch, or to corrupt the EPS.

Anyway, please let me know if this appears to solve part or all of the problems. Also please let MathWorks know about this so that they could tell the developers assigned to this bug of my findings and workaround.

phwi commented

@altmany I tried to check the new print2eps.m file and compare it to the old one by using the following code in MATLAB R2015a:

[X,Y,Z] = peaks(100);
[~,ch] = contourf(X,Y,Z);
ch.LineStyle = 'none';
ch.LevelStep = ch.LevelStep/10;
colormap('hot')
export_fig('Abbildung_original','-eps', '-transparent', '-q101', '-RGB');

and then changed the print2eps.m content to the old content without the fix and used:
export_fig('Abbildung_fixed_triangles','-eps', '-transparent', '-q101', '-RGB');

This is what I got (see attachment):
fix_no_fix

so in this case I don't see any change at all. Do I have to exchange more than the print2eps.m file in order to make the fix work? Or does the fix only work for certain artifacts, which somehow don't occur in the example I've been choosing? Somehow it seems as if in my example are no triangles at all when exporting to *.eps --> in the test case it doesn't matter if I use the fix or not. --> maybe I'll have to try it for some other cases.

There is no need to go as far as peaks(100) - the problem appears quite vividly in peaks(3) for example:
image

Or an even simpler test example:

[~,ch]=contourf(magic(2));
set(ch,'LineStyle','none');
set(gca,'Visible','off');
colormap hot; 
export_fig test.eps; winopen test.eps
print(gcf,'-depsc2','test.eps'); winopen test.eps  % prove that the artifacts come from print()

So it seems that there may be several possibly-unrelated problems with the print function in HG2 (R2014b+):

  1. diagonal white lines crossing single-color rectangles (this was hopefully solved above)
  2. horizontal/vertical lines across the image, whose cause is stil undetermined
  3. lines at various angles at the boundary between polygons of different colors

The search continues...

phwi commented

@altmany Ok I See, thanks for the separation of the three sources of issues and which of them is solved by your fix. Now I know that the issue that (actually) bothers me most is the third point. The hor/vert lines are ugly but not that bad because of a sort of regularity. And thanks for fixing one of the issues --> It should fix the problem of @jakobrdl I suppose.

In Adobe
Edit -> Preference -> Page Display -> un tick "smooth line art" and "smooth images". It then displays the correctly for me.

http://www.mathworks.com/matlabcentral/answers/15388-artifacts-in-figures-exported-as-pdf-from-matlab

I hope this helps for some of you. Annoying issue.

phwi commented

Hey @enigmaldc - I forgot to mention it here but Mathworks gave me exactly the same hint, which CAN be indeed useful but does not guarantee to solve the problem (maybe a 90 % solution). Anyway, it seems like such a poor workaround to me and a totally unsatisfactory solution by Mathworks. PDF was created for interoperability and operating system independence in a broader sense. It is a pain in the *** telling someone "[...] see my paper attached but before you can read it, you'll have to find out how to manipulate anti-aliasing and some other graphic settings in your desired *pdf-viewer [...]". On tablets and smartphones (yes, sometimes I read papers there indeed) there is no such thing as settings to change anti-aliasing behaviour but the graphics display get's messed up in the same way...

Thanks anyway for the crossreference and the suggested solution (that works most often but not always(!)).

Hello,

I have similar issues exporting figures generated using 'surf' or 'patch' and exporting as PDF. I have been using a previous version of export_fig (not sure where to find the version number, but the copyright only has "Oliver J Woodford" listed).

I noticed that with the current version, even if I specify "pdf" as output, I get a figure that appears to be tiled bitmaps. In addition, you can see the lines where the tiles do not exactly touch. I can delete these tiles separately in Inkscape. I've attached an image that I converted from PDF to PNG using GIMP. Also, I now have to specify 'nocrop', otherwise the image is cut off at both ends. In the previous version, I never had to specify 'nocrop' to get the full image. Is this intended behavior?

drift_test

To get the original behavior of full vectorized output (albeit with annoying triangles), I have to specify 'painters'. Is this the intended behavior? It seems strange to specify PDF and get a bitmapped output.

Currently, it seems like the default behavior for the previous version makes more sense (a vectorized output for pdfs and no image cropping), so I will continue using the older version for now.

Thank you!

I have this bug as well after updating to 2015b - if I knew about it I would have stayed with R2012b :(

The responses from MathWorks are infuriating, they have introduced a method that creates much bigger vector files that are, in addition, unusable for publication / sharing. Yet they refuse to acknowledge the problem and offer the "solution" of meddling with the settings of the reader app.

Is there any way of at least starting post-R2012b MATLAB with the original graphics engine to properly export these kind of vector figures? Because the newer versions are totally unusable:

problem

@JorgeGT - there is no way (at least none that I'm aware of) to use the old graphics engine in R2014b or newer Matlab releases.

@altmany Thanks, I guess I will have to go to the IT guys to see if they have installers for older versions! Thanks for your quick response and for the effort you're putting in export_fig!

Sbte commented

Hey all. I also ran into this bug, and when searching for the solution found this post. Since no one seems to have a solution, I tried to fix it myself, and managed to create a script that at least works for me. It fixes all artefacts in any PDF viewer that I tried, and also makes the EPS files a lot smaller. I hope it also helps some of you!

https://github.com/Sbte/fix_matlab_eps

@Sbte - if you could convert your Python script into Matlab code (which should not be too difficult), then I could integrate it into export_fig - can you do that?

Sbte commented

You'd still need to use system() to call Inkscape, is that a problem? If not then I can see what I can do. I just wrote it in Python, because parsing files/text is much easier in Python than in Matlab...

Also, did you test it yourself? As I stated in my README, so far I only checked it on my system. Any feedback would be welcome.

@Sbte Can confirm it works for me, awesome work! I used:

print(gcf,'temp','-depsc2')
system('python fix_matlab_eps.py temp.eps temp2.eps');
eps2pdf('temp2.eps',[fileName '.pdf'],1)
delete temp.eps temp2.eps

And the result was:
captura

The only issue I had was that the right colorbar has a small diagonal line remaining.But I'm looking to style the colorbar better so it's not a problem for me!

@JorgeGT You might know this already, but the diagonal line in the color bar is thankfully easy to fix in Inkscape. You just need to select it and "ungroup" it (CTL+SHIFT+G) completely. It seems like a separate bug.

Sbte commented

@JorgeGT Half of my code is actually there just to fix the colorbar. Would you mind sharing the eps that Matlab generated so I can have a look? It might just be that the code that Inkscape makes from it doesn't always look the same. At the moment I find it by looking for

Q
  Q
Q

so that doesn't seem very robust...

@nodice73 Thanks, I didn't know that!
@Sbte Here it is. And thanks again, you've made my day! :)

Sbte commented

@JorgeGT I just tried it and apparently I had already fixed it in the last version that I had. Enjoy!

hk66 commented

@Sbte Thanks for your code. I wanted to use your python code for an .eps file which has not been generated by matlab(attached here). I have this error:
"Traceback (most recent call last):
File "fix_matlab_eps.py", line 121, in
main()
File "fix_matlab_eps.py", line 56, in main
up_to_m = last[0].split('m')[0]
IndexError: list index out of range"

Could you please check it?
test.eps.zip

jkpld commented

A possible work around for 2d color data is to display it as an image instead of a surface/contour using image/imagesc. Just take your surface data, interpolate it onto a (dense) grid and plot as an image (need to scale the image to fit to your data axes). Using this method I do not get any of the white lines when exporting.

However, dotted and dashed lines, as well as the grid lines, are not exported correctly (grid lines become dotted, dashed/dotted lines become solid,...). From what the export_fig package says, I guess this means these lines are not being rendered with painters (though the image is still vector).

To get around this issue I just create a second axis on top of the axes I put the image in, set this axis color to none, set the ticks and limits to be the same, and plot any lines in this axis. The lines and grid lines render correctly now.

Hello,

I was wondering if this problem is somewhat related to an issue I have started running into when exporting matlab figures to eps/pdf?

There some of the lines seem to have sharp edges- particularly noticable for example in patches (this one was exported using the fill() command, but it does not really matter how you produce the form).

matlab_bug_1

Noticeably if you open the file in inkscape and ungroup you receive separate lines (of course you can unite them and then delete some points, but that's an awful lot of effort).
Also far more annoying is the fact that at these corners points of the red filled area are connected in a zig-zag-scheme (jumping from the bottom line to the top and back down, leading to the noticeable artifacts )

Edit: I forgot to mention (and this might be of relevancy) that the script plot2svg does NOT produce the same problems (however it does not support colorbars and legends as of 2014b)

I noticed that in the README file, there is a "Known issue" for "Lines in patch objects". The explanation in the README is

This issue is a feature of the software used to display the PDF, rather than the PDF itself.

I know this is MATLAB's official "answer", but it is clearly false. People with this problem can see the lines and can make them go away when they manually edit the vectors in Inkscape.

May I suggest changing that explanation to "this is a bug in MATLAB's vector rendering code" or something similar?

I can see similar behaviour with scatter plots as well, circles turn into hexagons and you can see the white lines on it. Here are examples:

ex

And zoomed in:
ex2

@nodice73 - good point, done

@mfedoten - I believe that this is an unrelated issue, that is due to the way that Matlab renders, using decagons (not hexagons) as an approximation for circles. This is not something that export_fig should realistically be expected to solve... You should really contact MathWorks to complain about it - export_fig is not a general solution for all of Matlab's internal print deficiencies...

I have also tried the fix_matlab_eps.py, launching it from command prompt on Windows 7, and it worked fine. However, when I tried to launch it directly from MATLAB using the command system as JorgeJT mentioned in a post above, the execution passes the line prompting the version of Inkscape and just get stucked there, without giving any error (I waited more than a couple of minutes for a single image, while launching invoking the script from the command prompt returned a successful output after some 5 seconds). Any idea of why this happens?

Has anyone got any decent answer from Mathworks on this topic?
It is completely insane that Matlab has lost its only (?) option to export decent vector graphics of scientific plots -.-
My bug request on fragmentary vector graphics (#01887614) resulted as enhancement request to their developers....
And wind is howling in a Q&A section. why-is-vector-graphics-chopped-into-pieces
Is eps output really soO insignificant >.< ?

My approach to dealing with this issue is a bit different. My need for the EPS or PDF file is for import into Illustrator where I can further develop the graphics. I then export from Illustrator into a PNG for use in Powerpoint. A workaround for this is to export the PNG at a very large size (6000 pixels on the long edge, for example) and then shrink the PNG within Powerpoint. The line is very thin at the large size and then disappears when shrunk down.

There are two separate issues with the Matlab export:

  1. The main thing that everyone notices is that patches are broken up into triangles, each of which is a separate path object if inspected in illustrator.
  2. Matlab sometimes adds extraneous 'cropping paths' that create an apparent white line even when there is no issue with fractured paths.

@Sbte - I'm listing here a few steps that are necessary for Mac / (first time inkscape) users in order to make your (https://github.com/Sbte/fix_matlab_eps) code work. Some of these things might be obvious to people already using eps, but since I had just been exporting to pdf and going to illustrator, I had to figure out a couple things.


---Steps needed for running 'fix_matlab_eps.py'---

  1. After following all install instructions for Inkscape and XQuartz it was necessary for me to create a symlink for Inkscape in the PATH :
ln -s /Applications/Inkscape.app/Contents/Resources/bin/inkscape   /usr/local/bin/inkscape

(and be sure to link 'inkscape' not 'inkscape-bin')
(http://stackoverflow.com/questions/22085168/inkscape-command-line-where-is-it-on-mac)

  1. When testing python code that calls inkscape, specify full paths of image and vector files being loaded.
    (https://bugs.launchpad.net/inkscape/+bug/1449251)

  2. add '/usr/local/bin/' to the PATH in matlab
    (https://www.mathworks.com/help/matlab/matlab_external/run-external-commands-scripts-and-programs.html)

path1 = getenv('PATH')
path1 = [path1 ':/usr/local/bin']
setenv('PATH', path1)
!echo $PATH 
  1. repair libtiff library (this might have been specific to my machine)
    (kyamagu/mexopencv#250)
    [at bottom]

backed up original file to: /Applications/MATLAB_R2016a.app/bin/maci64/backup_libtiff.5.dylib
simlinked from: /usr/local/opt/libtiff/lib/libtiff.5.dylib

  1. install ghostscript
    http://brewformulas.org/Ghostscript

Finally, I was able to run the conversion with fix_matlab_eps.py, however I don't think it worked. Can someone check if they can do the conversion on the following figure:

function image_output_scratchpad()
%%% trying to fix matlabs pdf/eps output
%%% using (https://github.com/Sbte/fix_matlab_eps)

P = mfilename('fullpath');
base_dir = fileparts(P);
cd(base_dir);

figure;
[X,Y,Z] = peaks(100);
[~,ch] = contourf(X,Y,Z);
ch.LineStyle = 'none';
ch.LevelStep = ch.LevelStep/10;
colormap('hot')
imgSvNm = 'peaks';
print(gcf,imgSvNm,'-depsc2')

fname_input = [base_dir,filesep,imgSvNm,'.eps'];
fname_output = [base_dir,filesep,imgSvNm,'_fixed.eps'];
system(['python fix_matlab_eps.py ',fname_input,' ',fname_output]);
eps2pdf(fname_output,'/usr/local/bin/gs',1);

Here is what I get.
The Initial eps output from Matlab:

alt peaks.pdf

And here is what I get from running 'fix_matlab_eps.py':

alt peaks_fixed.pdf

*** I created my own work around which is very similar to 'fix_matlab_eps.py'. I'm doing essentially the same thing to pdfs with illustrator: find all the paths of the same color and unite them. The problem is that this requires running a .jsx Javascript function through ExtendScript Toolkit with Adobe Illustrator open, simulating actions as though they were going through the UI manually and it takes forever to run (like hours). On the plus side, it has worked on all the cases that I've tested so far.

After my javascript hack:

alt temp2.pdf

Isn't it amazing what it must be done just to fix a crippling mistake that MathWorks refuses to address for its paying customers? Not to speak about how this worked perfectly in the original graphics engine, producing lightweight figures without artifacts...

@JorgeGT it's ridiculous.

@Sbte, @JorgeGT, @dfarrel1 - can any of you convert @Sbte's python script into Matlab and integrate it with @dfarrel1's additions into export_fig (or more specifically, print2eps.m)? I'll be delighted to incorporate it into the baseline version.

I'd do it myself but my knowledge of python and EPS is sketchy and I don't have a Mac nor Illustrator, so I'm likely to do more harm than good if I tried to do it myself...

@altmany that might be possible, but why bother? you can just package fix_matlab_eps.py with your export_fig.m code and call the python script from Matlab, from export_fig. That introduces python into the mix, but all the other steps (install inkscape + dependencies, make sure inkscape can be called from the command line, install ghostscript, navigate the weird bugs of these applications when testing them, etc) those are unavoidable and they make running a python script from matlab the most trivial step in the process. Also, isn't python already preinstalled for Macs and Linux anyways.

As far as my own hack goes, I didn't put it up (yet) and it will not be possible to translate it into matlab because only ExtendScript Toolkit running javascript .jsx files (I guess you can also use Visual Basic on Windows, and Applescript on Macs) can talk to Adobe Illustrator programmatically.

Also I think that our hacks are messy workarounds that you maybe don't want to include into a well maintained and fully functioning package? The only true fix can come from Mathworks, but they insist that there is no problem.... so fat chance of that happening...

Another year with limited vector graphics usage .
Matlab 2017a release notes

I just put my fix up.
https://github.com/dfarrel1/fix_matlab_vector_graphics

It's not perfect, but I hope it helps some of you.

I tried to fix this issue in EPS files with Matlab-only code:
https://github.com/Conclusio/matlab-epsclean

It is not an efficient implementation (performance-wise) but works for all the examples I provided and the use cases I have.

It seems that this issue is partially solved in next release of MATLAB.
At least the original problem of @phwi with the contourf plots seems to be fixed :)

See my post and tests with MATLAB R2017b prerelease vector output

edit:
Since the R2017b prerelease is subject which is not desired to be discussed in MATLAB's Central
I guess I can re post it here.

  • Some hands on test show that contourf paches will be unified. No more rectangles, triangels etc..
  • Lines ploted with contour are still just grouped small (~3..6 pointed) polygons.
  • Lines polted with simple plot command are unified, thus one can use contourc+plot command to get same results as with contour.
  • Colorbars are still mess. Constructed from 2 separate triangles, leaving antialiasing handle the white gap between them.
  • Saving pcolor plots in vector format is still not a good idea. :) The plot gets meshed into elements depending on the number of colors used (?).

Hopefully we see those and many other improvements in official release in fall (?). Fingers crossed.

epstest_r2017b

Ok, Mathworks have released the Matlab 2017b. Does anyone have a chance to test if this issue got fixed from MathWorks? Thanks!

Hey, so I just tried plotting some contours with the freshly installed 2017b and using export_fig with -painters (because my 2012a version is not working anymore) and I think it has been fixed indeed! Can someone else confirm?

I also tried using the minimal example

contourf(peaks(100));saveas(gcf,'figure.eps','epsc')

and got the following (using preview in OSX High Sierra to open the .eps and then exporting it to .pdf before uploading it here): figure.pdf

I just installed Matlab 2017b and made some trials. It doesn't seem to fix the problem for me.

Code:

contourf(peaks(100));export_fig('figure1','-eps','-pdf','-painters');
contourf(peaks(100));export_fig('figure2','-eps','-pdf','-opengl');

Files:
figure1.pdf
figure2.pdf

Screenshot:
capture0

Recap on the issues:

  1. With -painters, the white lines between patch objects still persist.
  2. With -opengl on my Thinkpad P50 Windows 10 machine, figures still look a little rough and they are not as good as vector images, of course.
  3. Using export_fig and saveas give the same result, essentially.

My OpenGL version info:

Version: '4.5.0 NVIDIA 382.05'
                           Vendor: 'NVIDIA Corporation'
                         Renderer: 'Quadro M1000M/PCIe/SSE2'
            RendererDriverVersion: '22.21.13.8205'
        RendererDriverReleaseDate: '01-May-2017'
MaxTextureSize: 16384
                           Visual: 'Visual 0x07, (RGBA 32 bits (8 8 8 8), Z depth 16 bits, Hardware acceleration, Double buffer, Antialias 8 samples)'
                         Software: 'false'
             HardwareSupportLevel: 'full'
        SupportsGraphicsSmoothing: 1
    SupportsDepthPeelTransparency: 1
       SupportsAlignVertexCenters: 1
                       Extensions: {333Γ—1 cell}
               MaxFrameBufferSize: 16384

@briochemc You said you export the eps to pdf using some preview software. What is the name of the preview software? I can try again if I have the software on my computer. Thanks.

@i2000s "Preview" is the name of the image/pdf viewer of Mac OS X. Sad to hear that the bug is still present in the pdf files... Can you upload the .eps files? I can try to convert them to pdf with Adobe Distiller to check.

figures.zip
Thanks.

Sadly I can confirm that with Distiller the results are the same as yours, bug still present....
figure1.pdf
figure2.pdf

Whooooops! I made a mistake, I was actually using 2017a instead of 2017b on Windows 10.
Switching to Ubuntu 16.04 and using Matlab v9.3.0.713579 (R2017b), it seems the issue has been fixed, indeed... Sorry for the confusion.

So far, the only issue to me is the lines are actually segments with sharp edges. See the attached eps files. PDFs are also available generated from export_fig.

figures2017b.zip
figure1.pdf
figure2.pdf

I just tried a few other plots, as confirmed from the 2017b prerelease, a few other issues don't seem to have been fixed to this end. For example, pcolor is not working well for exporting figures,

figure(1); pcolor(peaks(100)); shading interp;
saveas(gcf,'figure3','epsc')
epsclean('figure3.eps','figure3_clean.eps','CombineAreas',true,'RemoveBoxes',true)
export_fig('figure4','-eps','-pdf','-painters')
export_fig('figure5','-eps','-pdf','-opengl')
epsclean('figure5.eps','figure5_clean.eps','CombineAreas',true,'RemoveBoxes',true)

generate the following plots (only pdf allowed on github):

figure3.pdf

figure4.pdf

figure5.pdf

Similarly, for surf plots using -painters and -opengl:

figure6.pdf

figure7.pdf

I was excited thinking that 2017b would fix the issue, but alas, I still have the white line etching in many of my eps files.

The best workaround I've found to get a smaller vector file without the white line etching is to follow Elmar Plischke's post from 11 Aug 2016 on this matlab thread and then follow it up in Illustrator (though Preview/other viewers should be fine too) following e-create's response on this thread.

My workflow:

  1. Save the figure as a eps file (using print command)
  2. Using a text editor, change the line in the eps header from
    /f/fill ld
    to
    /f{GS 1 LW S GR fill}bd
    and move the line down several lines, to right below the "/LW/setlinewidth ld" line
    From here, your eps file should display fine on all pdf viewers.
  3. To make the file smaller (while keeping it vectorized), I then open this modified eps file in Illustrator (or Preview) and save the file as a PDF (in preview, use Export as PDF). In Illustrator, make sure all the Options are unselected (especially "Preserve Illustrator Editing Capabilities", but it's fine to select "Optimize for Fast Web View").

I wish matlab would just correct this...too many steps to make a figure look like it does when it's on your screen in matlab. Yes, matlab is correct that you can make it look better in each pdf viewer by playing around with preferences. But, I want to know that a figure is going to look how I intended it to - no matter who is opening it and with what software and settings and preferences. It shouldn't be on individual people to modify their pdf viewer settings individually to correctly display our figures because of how matlab renders them when using print.

@ambramson, thanks for this, very useful. Your advice fixes the issues I was having. This little code does step 2 in one go:

#/bin/bash
line=$(sed -n '/\/f\/fill/'= $1)
linenew=$(sed -n '\/LW\/setlinewidth ld/'= $1)
if [ -z "$line" ]; then
    echo "File already fixed or not created by print command"
else
    echo "File fixed!"
    sed -i -e 's/\/f\/fill ld/\/f{GS 1 LW S GR fill}bd/' $1
    printf "$line m$linenew\nw\n" | ed $1
fi

save say to 'epsfix.sh', make executable, and run as epsfix.sh yourepsfile.eps

As export_fig does not seem to produce the same EPS commands, it sounds like there's no way to produce 'fixable' eps files with export_fig for now, correct?

Thanks for everyone for contributing workarounds to the many iterations of buggy matlab. I do hope this issue is fixed by mathworks in the next release, as it's approaching 3 years! I'm not going to hold my breath on this one

The matlab function epsclean provided by @Conclusio above looks like a viable workaround. It works well when used alone, but it seems incompatible with export_fig in my case πŸ‘Ž
Here is my figure saved with a simple print(gcf,'-depsc','-painters','out.eps')
out
Here is the cleaned figure after epsclean('out.eps','clean.eps')
clean
So I tried to call this directly from within export_fig, adding three lines at the end of function print2eps
if any(strcmpi(options,'-painters')) && using_hg2 ; epsclean(name) ; end
But this removed some patches at the top of the figure:
clean_failed
That's reallly a pity because otherwise we would be able to solve once and for all this bug from within export_fig !

musm commented

Looks like this is still a problem with matlab 2018a.... sigh

@musm I haven't tried 2018a but for my 2017b solved this.

@musm Can you share script that didn't work for you?

Please see my post on this thread, dated 14 Apr 2018: Conclusio/matlab-epsclean#9
@Conclusio's suggestions did the trick for me. I have a neat process now that seems to have solved my various issues.

See related MathWorks official bug report, which lists this bug as being "solved in R2017b" (which of course it is still not): https://www.mathworks.com/support/bugreports/1174438:

Summary
Unexpected fine lines across graphics in PDF, PS, EPS and SVG files

Description
If you save a figure with MATLAB graphics to a PDF, PS, EPS, or SVG file and then open the saved file in a viewer application (such as Adobe Reader, GSView, or a web browser), unexpected fine lines can appear across filled areas. Zooming into the graphics does not eliminate the lines.

These lines are a side effect of anti-aliasing algorithms used by some viewer applications when displaying the shapes that MATLAB graphics creates in the files. The lines do not appear if you print the file to a paper copy because printers do not use anti-aliasing.

Fix
The current fix removes white lines that appear across any 2-D polygon object or geometry that is a single color. It is possible that the white lines still appear across other objects, such as a 2-D polygonal with textures or color gradients.

Workaround
You can remove the white lines in some viewing applications by disabling anti-aliasing for graphics objects. You can typically find the setting in a display-related options menu. Instructions for common applications are given below:

  • GSView
    Select Media > Display Settings
    Change the Graphics Alpha value to 1 bit

  • Adobe Reader XI
    Select Edit > Preferences
    Select the "Page Display" category in the list on the left
    Uncheck the "Smooth line art" option in the Rendering options panel on the right

These lines are a side effect of anti-aliasing algorithms used by some viewer applications when displaying the shapes that MATLAB graphics creates in the files.

It is almost funny, because it is almost true

Hi,
I got the same issues with exported vector graphic files.. I'm using *.pdf export and edit these files normally with adobe illustrator for some presentations. In illustrator, my picture is all over with these white lines at filled matlab plots like "pcolor". But that's just a representation problem.. If you turn off "smooth line art" in illustrator, the plot is shown correct. After I finished my editing, I normally want to export this vector graphic file to *.png (for word or powerpoint import) and the white lines are present again. But there is another setting for export: "supersampling". If this box is checked at the export settings, my *.png is presented without these white artefacts. Its just a possible solution for illustrator, but I'm sure that there are equivalent properties in other programs (altmany's post with the adobe reader workaround sounds very similar).

Best regards

Hi,
I'm getting the lines using version 2020a.
I think I've tried every workaround mentioned in this thread but nothing seems to work.
Does anybody manage to remove them? If so, could you please let me know how?
Thanks!

Hi,
I'm getting the lines using version 2020a.
I think I've tried every workaround mentioned in this thread but nothing seems to work.
Does anybody manage to remove them? If so, could you please let me know how?
Thanks!

Can you share script or code that is producing white lines, I have multiple contour plots & they seems to work fine, I can probably look into it if you can share your sample code

Thanks for the quick answer!
I've attached the figure, the code to generate it and an exported pdf.
I'm using export_fig('out.pdf') to generate the pdf.
The lines appear using version R2020a as well as R2019a on Windows and Ubuntu.
figure.zip

Thanks for the quick answer!
I've attached the figure, the code to generate it and an exported pdf.
I'm using export_fig('out.pdf') to generate the pdf.
The lines appear using version R2020a as well as R2019a on Windows and Ubuntu.
figure.zip

Yes, 3d surfaces can still have a problem, one solution that I found was to turn axes invisible first & then print surface only. Afterward, turn surface invisible and print axes only & then merge them manually using illustrator or any other vector editors. try that & Let me know if that help

Thanks so much, works perfectly!

Great!, Just for future reference, if anyone is printing charts that are 3d, then they need to print all objects separately and then use an external tool to merge them, for e.g. if you had a surface, line, and axes then you will need to print them separately and then merge them manually.

I recommend a much easier option, useing 'ContentType','vector' of https://de.mathworks.com/help/matlab/ref/exportgraphics.html

%EPS
exportgraphics(gcf,'myVectorFile.eps','BackgroundColor','none','ContentType','vector')
%PDF
exportgraphics(gcf,'myVectorFile.pdf','BackgroundColor','none','ContentType','vector')

an example:

clear
close all
warning('off','MATLAB:print:ContentTypeImageSuggested')%turn off Warning (Vector is not slower than Raster)

gcf=figure(314159265);
sphere %plot3(X,Y,Z) %Plot your awesome plot
daspect([1 1 1])%enssure that it is not distorted

%% Uggly RasterOutput
disp('Rasterouptut')
print('-depsc','-tiff','-r300','UgglyRaster.eps')%uggly: Rastergraphics
print('-dpdf','UgglyRaster.pdf')%uggly: Rastergraphics

%% Vector Output1 (no border for PDF, and optional transparent background)
disp('exportgraphics')%for R2020a or newer https://de.mathworks.com/help/matlab/ref/exportgraphics.html
exportgraphics(gcf,'myVectorFile1.eps','BackgroundColor','none','ContentType','vector')
exportgraphics(gcf,'myVectorFile1.pdf','BackgroundColor','none','ContentType','vector')

%% Vector Output2
disp('-vector')%In R2022a -painters got replaced by -vector
print('-depsc','-tiff','-r300', '-painters','myVectorFile2.eps')%large filesize
print('-dpdf','-r300', '-painters','myVectorFile2.pdf')%uggly: has large white borders

%% Vector Ouptut3
disp('Painters') %https://www.mathworks.com/matlabcentral/answers/92521-why-does-matlab-not-export-eps-files-properly
set(gcf,'renderer','Painters')
print('-depsc','myVectorFile3.eps')%white background which is exeedes the eps-border, not transparent
print('-dpdf','myVectorFile3.pdf')%uggly: has large white borders

I recommend a much easier option, useing 'ContentType','vector' of https://de.mathworks.com/help/matlab/ref/exportgraphics.html

%EPS
exportgraphics(gcf,'myVectorFile.eps','BackgroundColor','none','ContentType','vector')
%PDF
exportgraphics(gcf,'myVectorFile.pdf','BackgroundColor','none','ContentType','vector')

an example:

clear
close all
warning('off','MATLAB:print:ContentTypeImageSuggested')%turn off Warning (Vector is not slower than Raster)

gcf=figure(314159265);
sphere %plot3(X,Y,Z) %Plot your awesome plot
daspect([1 1 1])%assure that it is not distored

%% Uggly RasterOutput
disp('Rasterouptut')
print('-depsc','-tiff','-r300','UgglyRaster.eps')%uggly: Rastergraphics
print('-dpdf','UgglyRaster.pdf')%uggly: Rastergraphics

%% Vector Output1 (no border for PDF, and optional transparent background)
disp('exportgraphics')%for R2020a or newer https://de.mathworks.com/help/matlab/ref/exportgraphics.html
exportgraphics(gcf,'myVectorFile1.eps','BackgroundColor','none','ContentType','vector')
exportgraphics(gcf,'myVectorFile1.pdf','BackgroundColor','none','ContentType','vector')

%% Vector Output2
disp('-vector')%In R2022a -painters got replaced by -vector
print('-depsc','-tiff','-r300', '-painters','myVectorFile2.eps')%large filesize
print('-dpdf','-r300', '-painters','myVectorFile2.pdf')%uggly: has large white borders

%% Vector Ouptut3
disp('Painters') %https://www.mathworks.com/matlabcentral/answers/92521-why-does-matlab-not-export-eps-files-properly
set(gcf,'renderer','Painters')
print('-depsc','myVectorFile3.eps')%white background which is exeedes the eps-border, not transparent
print('-dpdf','myVectorFile3.pdf')%uggly: has large white borders

It works! β€œexportgraphics” was released in 2020a. I thought it was a small bug, but it takes 6 years to fix...