Printing a transparent figure in MATLAB's terminal emulation mode - matlab

Is it possible? The code below illustrates what I want to do:
xdata = [0 1 2];
ydata = [0 1 0];
h = patch(xdata,ydata,'w');
set(h, 'FaceAlpha', 0.2);
print -dpng myfig
If I start MATLAB using option -nodisplay and run the code above, MATLAB simply gives me a core dump. I think that MATLAB should behave a bit better than crashing without further explanations, but I understand that this is due to the fact that neither the opengl nor the zbuffer renderers are available in terminal emulation mode.
I am getting around this problem by plotting the transparent figures in .svg format but this is not an ideal solution for me. My MATLAB scripts are generating HTML reports with many embedded figures and most browsers perform very poorly when rendering pages that contain several (relatively complex) .svg images. So, does anyone know of a better solution?

An indirect solution to this problem is to print the transparent figures to a .svg file using plot2svg(), and then use Inkscape to convert the .svg file to .png, .pdf or any other format supported by Inkscape. Inkscape offers quite good command line support so you can easily script the whole process from MATLAB. Inkscape is available in Windows, Linux and Mac OS X.

Related

How can I make my plots look prettier (including fonts, label, etc )?

I am trying to obtain very nice plots for my presentation below is a code that I used to plot
clear all
clc
close all
syms v
omegat= -2:0.000001:2;
Nt=32;
gainfuc = (1/Nt)*exp(1i*pi*omegat*(Nt-1)/2).*sin(pi*Nt*omegat/2)./sin(pi*omegat/2);
gainfuc(omegat == 0) = 1;
G = (omegat < 2/Nt).*(omegat > -2/Nt);
plot(omegat,abs(gainfuc))
syms t
hold on
grid on
plot(omegat,G,'r')
ylabel('G_t(y)','FontSize',16,'FontWeight','bold')
xlabel('y','FontSize',16,'FontWeight','bold')
My question is quite simple, any ideas to make this plot nicer (font, grids, etc...) so that it would look nice in presentations?
Update
I have obtained the following figure after the changes recommended in the answer below
In Matlab 2014b a new graphic engine got introduced, it immediately looks more pretty.
New default colormap presents data more accurately, making it easier to interpret. New default line colors, fonts, and styles with anti-aliased graphics and fonts improve the clarity and aesthetics of MATLAB visualizations.
In Matlab 2014a you can also activate the new graphics engine by following these instructions.
In earlier versions the hack is may also possible, but I haven't tested it. It is most likely quite buggy. For 2014a I use it for almost a year now and it works like a charm. I couldn't find any differences to the final release of HG2 in 2014b.
Make sure that smoothing is set to 'on'
h = gcf;
h.GraphicsSmoothing = 'on'
I also used the standard LateX font CMU Serif Roman to spice everything up. Enter this lines at the beginning of your code after installing the fonts (open source).
set(0,'defaultAxesFontName', 'CMU Serif Roman')
set(0,'defaultAxesFontSize', 12)
General recommendations:
Use vector graphic renders: set(gcf, 'renderer', 'painters')
Specify the resolution when saving your plots, especially for pixel graphics: print('-dpng','-r600','PeaksSurface') (still use the vector renderer!)
The vector format for MS Office is .emf and is also supported by Matlab
May use: set(gcf,'InvertHardcopy','off')

Matlab: How to avoid artefacts in filled contour plots

I am trying to export filled contour plots from Matlab as vector graphics to include in a Latex file. My current methodology is:
contourf(x,y,v_mag,20), axis([0,width,0,height]),daspect('manual') ;
grid off
colormap jet
h = colorbar;
caxis([0 v_lid])
h.Label.String = 'Velocity Magnitude (m/s)';
set(gcf,'renderer','painters')
export_fig('-painters', '-transparent', 'pdf', 'filename.pdf');
The problem with this method is that it produces artefacts (the white lines) which look like the following:
I understand that these white lines are the polygons defining the shaded areas which have invisible edges, and don't quite overlap (according to here). The problem is caused by the pdf viewer itself which tries to smooth the lines displayed on the screen (according to here). My problem is that most people viewing the document will not know this and will not know how to prevent the viewer doing this. So my questions is:
Is it possible to create a vector graphic of a filled contour plot from Matlab without these artefacts?
Eps produces the same problems. I have tried to use the SVG function but have not had any luck. I am trying to avoid using raster graphics due to the pixelation caused by zooming in. Any advice would be much appreciated.
EDIT - Additional info - Using Matlab v.2014b and Ghostscript v.9.15
This is an extremely frustrating issue for which there seems to be no solution (or even, few attempts at a solution), and it has been many years now. In summary, Matlab cannot cope with outputting artefact-free contour or surface plots (anything with complicated meshes or transparencies).
I can suggest a simple workaround that will work in most cases, where the colours or details of the underlying contour plot do not need to be preserved perfectly.
Output a version of the figure without lines in png format with high enough resolution.
Output a version of the figure without colours in pdf format. This should be free of any artefacts. If your figure it complicated and has many transparencies, you may need to output multiple versions building up the 'levels'.
Use Adobe Illustrator (or some equivalent) to perform a vectorized trace of the raster image. You may lose some detail here, but for simple contour plots with limited details, it will be converted easily to vectorized form.
Overlay the two images within Illustrator. Output in vector format.
This also allows you to use things like Illustrator's ability to compress pdfs.
If you don't want to toy with vectorizing the raster output, you can also simply replace steps 3-4 and combine a raster colour image with a vectorized line image. This would work well for complicated contour plots giving you crisp lines, but the ability to compress the underlying colours.
Eventually, MatLab 2013b doesn't have this problem. Furthermore the files it produces has much less volume. That is because MatLab 2013b composes vectorized image of big overlapping figures, while MatLab 2014b makes that awful meshing.
Here the first file was got with 2013b and the second with MatLab 2014b (I highlighted one of the polygons with red stroke to show the difference). The volumes differ in approximately 22 times (38 Kb vs. 844 Kb).
So it is not the viewer problem, it's how the image is exported from MatLab.
The issue is also discussed here Triangular split patches with painters renderer in MATLAB 2014b and above, but still no direct solution.

Colorbar not appearing in (surface) plot - LaTeX interpreter issue

As the title states, the colorbar in surface plots does not appear when the default interpreter is set to 'latex'. This occurs in MATLAB 2012b and 2013a and on two different machines.
Precisely, the colorbar object is created, can be clicked when editing the plot, can be edited using the interactive colorbar editor but is not visible at all.
It does not appear when saved as a figure and reopened, saved as a PNG, exported in .eps format or saved as a .pdf.
After searching around, I found the following post from 2011, concerning MATLAB 7:
http://mathforum.org/kb/message.jspa?messageID=7518470
Specifically, the interpreter appears to be at fault, when it is set to 'latex', the colorbar will not display. When set to the default, it does.
Here is the smallest demonstrating example.
set(0,'defaulttextinterpreter','none');
figure;
surf(peaks(100)); colorbar
set(0,'defaulttextinterpreter','latex');
figure
surf(peaks(100)); colorbar
The two figures are identical except that the colorbar is visible only in the first figure.
I use a lot of special characters and sub/superscripts in my plots so in startup.m I set the default interpreter to 'latex'. I could surround all calls to colorbar with:
set(0,'defaulttextinterpreter','none');
colorbar;
set(0,'defaulttextinterpreter','latex');
But this is probably the least elegant solution possible. Can anyone shed some light on this issue which appears to be extant for over 5 years and multiple editions of MATLAB?
This behaviour is gone in Matlab R2014b, which uses an entirely new graphics engine, hg2. The plots look different (most of the time in a better way), but instead of old, documented bugs, there are now new, undocumented bugs...
Earlier versions of Matlab support somewhat experimental stages of hg2. You can enable these by running Matlab with the switch "-hgVersion 2". You can do this, for example, by editing the Desktop shortcut to point to something like "C:\Program Files\MATLAB\R2013b\bin\matlab.exe" -hgVersion 2.
Unfortunately, with the new graphics engine being the default in Matlab2014b, the old bugs are less likely to be fixed in the future. I wish I could help you in a better way, but the workaround you posted seems like a good solution, especially if you wrap it in a function called robust_colorbar or so.
I can reproduce the problem on my system (R2010b, Windows Vista 32 bits) . It seems to be solved by changing the 'Renderer' property of the figure from the default 'OpenGL' to either 'painters' or 'zbuffer'. So, you can either change the renderer when creating the figure:
set(0, 'defaulttextinterpreter', 'latex');
figure('Renderer', 'zbuffer') %// this line changed
surf(peaks(100)); colorbar
or change the default renderer to be used for all figures (so you don't need to change it in every figure):
set(0, 'DefaultFigureRenderer', 'zbuffer'); %// this line added
set(0, 'defaulttextinterpreter', 'latex');
figure
surf(peaks(100)); colorbar
Using a renderer other than 'OpenGL' may affect features such as transparency or drawing speed. Here's some information about pros and cons of each renderer.

Axes background color not rendering properly when exporting videos

Running Matlab R2011b under Linux, I am generating a video using the VideoWriter. My code goes something like this:
h_fig = figure();
set(h_fig, 'Visible', 'on')
set(h_fig, 'Position', [300,200,898,720]);
h_axs = axes('Parent', h_fig);
set(h_axs,'nextplot','replacechildren');
vidObj = VideoWriter('leadfollow3.avi');
...
for i = 1:n
h_axs_a = subplot(3,2,[1 2]);
plot(h_axs_a, x, a_mag_lead, x, a_mag_follow, 'r');
...
The plot is composed of several subplots. The first subplot renders fine, but for the rest, the axes background remains grey instead of white. What's worse, for certain frames it switches to white, leading to annoying flicker in the video (see example video here). Individual plots outside the video writer loop don't display this artifact. What might be the best strategy to troubleshoot this?
Edit: after I got a chance to try this code on Windows, it seems that the problem is restricted to Linux. Nonetheless, I would still very much like to know a possible solution, since I do not have regular access to Windows boxes where I could do my computations.
You missed the crucial lines of code where you actually turn the figure into an image and send it to the VideoWriter, so it's difficult to be of much help. However, if you're not doing so already, I suggest you use export_fig for this task.

Small eps figure size in Matlab

How to create a small eps file from a Matlab figure? I use LaTeX and the eps that I'm getting with Matlab (R2010a) is of the order 6 MB. How to set the plot options to give an eps figure of smaller size?
Does the render options painters or zbuffer help?
Thanks a lot...
One additional info: I use Laprint to generate my eps figures. So, I end up with 2 files: 1 tex file with information about the labels etc and one eps file which is just for the drawing itself. I use Laprint as I can write mathematical expressions in my labels and with a simple command in LaTeX, I can change the size of the fonts easily. Also I can have the default LaTeX fonts in the labels.
Don't use eps. Use pdf format instead, and compile your LaTeX file with pdflatex.
Does the render options painters or zbuffer help?
Does that mean that you're using OpenGL? If so, then what you're getting is a Postscript file which contains an image. Postscript is a good choice for vector images, but OpenGL can't generate vector images. If you really need the OpenGL renderer for something, then you might as well use a bitmap image format. If you really want to take advantage of EPS (or any other Postscript flavor), then you'll want to use Painters.