Exporting eps from MATLAB - matlab

I am trying to produce high quality EPS files (1000 dpi) for an Elsevier journal. I have been using export_fig, but when I try to view the files, they are squished and distorted. Does anyone know to produce an eps that looks the same as the figure on the screen?

When I was exporting eps figures I had a lot of success using
Oliver Woodford's function export_fig found on mathworks file exchange.
He has updated it since I used it, but it's probably only gotten better.

I have a set of steps that I follow for my publications that has never failed me so far. I am including all the steps which might be more that what you are asking for. Here it is
1.Plot with the correct linewidth and/or marker size
2.Set font size
3.Set X and Y lims
4.Set X and Y ticks
5.Set X and Y tick labels if appropriate
6.Set X and Y axis labels
7.Set units of the figure to inches
8.Set the size of the figure
9.Export using export_fig with the -painters option
hf = figure();
plot(x,y,'Linewidth',1);
set(gca,'FontSize',8);
xlim([a,b]);
ylim([c,d]);
set(gca,'XTick',a:ab:b);
set(gca,'YTick',c:cd:d);
xlabel('Xlabel');
ylabel('Ylabel');
set(gcf,'units','inches');
set(gcf,'Position',[0 0 fig_width fig_height]);
export_fig(filename,'-transparent','-eps','-painters');
The final -painters is important since sometimes dashed and dot-dash linstyles don't get exported correctly. The same method works with -pdf too.

You can use hgexport.
x = 0:.1:pi;
h = figure();
plot(x, sin(x));
hgexport(h, 'sin.eps');
UPDATE
print and saveas also work.

Related

MATLAB: how to save a geoshow figure with faceAlpha?

I am trying to save a figure in Matlab R2014a in which I want to plot data over an Image. This is the code:
[Singapore, R] = geotiffread(file);
s = size(Singapore);
matrix = rand(s(1),s(2));
geoshow(Singapore(:,:,1:3), R)
hold on
geoshow(matrix, R, 'DisplayType', 'texturemap','facealpha',.2);
xlim([103.605,104.04])
ylim([1.2,1.475])
This one is the plot that works perfectly:
While when I am printing the figure
print(gcf, '-dpng', fullfile(FileF, 'test.png'))
the image is completely white
Many thanks for the image link!
I have tried your code (adapted for the `Singapore.tif' file you provided and an appropriate output file) and it works as expected on my system (Matlab 2013b, Linux 64-bit). This is the output file:
So I'm sorry to say that there's nothing wrong with your code, and it's probably something to do with the 'png' driver on windows or your particular installation. Have you tried printing to a different driver? (e.g. jpg or pdf?). Does it actually work if you do this from the figure's graphical menu, i.e. File->Save As; or via File->Export Setup->Export with appropriate properties?
The only other thing I can think of which may be confusing your system is the attempt to print a uint8 rgb image (your Singapore image) and an overlayed double grayscale image. You can see if converting your Singapore image to double solves this by changing:
geoshow(Singapore(:,:,1:3), R)
to
geoshow(mat2gray(Singapore(:,:,1:3)), R)
Might also be worth trying to plot the data manually and see if printing that works, e.g.:
[Singapore, R] = geotiffread('Singapore.tif');
SingaporeXYImage = cat(3, flipud(Singapore(:,:,1)), ...
flipud(Singapore(:,:,2)), ...
flipud(Singapore(:,:,3)));
s = size(Singapore);
matrix3D = repmat( rand(s(1),s(2)), [1,1,3]);
imagesc(R.LongitudeLimits, R.LatitudeLimits, mat2gray(SingaporeXYImage));
hold on;
imagesc(R.LongitudeLimits, R.LatitudeLimits, matrix3D, 'alphadata', .2);
hold off;
axis xy equal tight;
xlim([103.605,104.04])
ylim([1.2,1.475])
print(gcf, '-dpng', 'test.png');
As a bonus, here's how you might perform the same thing in Octave, in case you're interested (I find printed plots from Octave look much nicer, especially in terms of fonts!):
pkg load mapping;
pkg load image;
[SingaporeStruct, R] = rasterread('Singapore.tif');
SingaporeImage = cat(3, SingaporeStruct(1:3).data); % note this is a matrix of
% "doubles" in range [0,255]
SingaporeImage = mat2gray(SingaporeImage); % Convert to appropriate [0,1] range
% for "doubles" rgb images!
s = size (SingaporeImage);
matrix3D = repmat (rand (s(1), s(2)), [1, 1, 3]);
imagesc (R.bbox(:,1), R.bbox(:,2), ...
SingaporeImage .* 0.8 + matrix3D .* 0.2); % manually create
% transparency effect
axis xy equal tight
xlim([103.605,104.04])
ylim([1.2,1.475])
print (gcf, '-dpng', 'test.png');
Also, no disrespect to my colleague and the effort he / she put into his / her answer, but I will note that the other answer you received is essentially completely wrong and you should retract your marked accepted regardless of his / her claim and warnings about how rude it is to retract a marked answer. mapshow is specifically used for images using a MapCellsReference format: the boston.tif image is one such image. Your image however uses a GeographicCellsReference format. mapshow is used for the former, geoshow is used for the latter; geoshow would have failed for boston.tif, in the same way mapshow fails for Singapore.tif. It should have been obvious your image is a "Geo" variant because your line geoshow(Singapore(:,:,1:3), R) worked without throwing an error. Therefore the suggestion to use mapshow is not the correct answer to your question, and is misleading. Not to mention it is completely irrelevant to your actual question about why the print command does not produce the expected result from its figure handle, which should in theory have nothing to do with how the figure was produced in the first place. I would have no qualms about retracting your "accepted" mark from it. Not least because this site functions as a reference for many other viewers; it does not make sense to direct users to the wrong answer just because you got bullied into accepting it.
As suggested by mathworks, using mapshow should solve your problem. The following works for me:
[boston, R] = geotiffread('boston.tif');
figure
mapshow(boston, R);
axis image off
S = size(boston);
matrix=rand(S(1),S(2));
hold on
mapshow(matrix, R,'DisplayType','texturemap','facealpha',0.2);
print(gcf, '-dpng','test.png') ;

How to specify the axis size when plotting figures in Matlab?

Suppose that I have 2 figures in MATLAB both of which plot data of size (512x512), however one figure is being plotted by an external program which is sets the axis parameters. The other is being plotted by me (using imagesc). Currently the figures, or rather, the axes are different sizes and my question is, how do I make them equal?.
The reason for my question, is that I would like to export them to pdf format for inclusion in a latex document, and I would like to have them be the same size without further processing.
Thanks in Advance, N
Edit: link to figures
figure 1: (big)
link to smaller figure (i.e. the one whose properties I would like to copy and apply to figure 1)
For this purpose use linkaxes():
% Load some data included with MATLAB
load clown
% Plot a histogram in the first subplot
figure
ax(1) = subplot(211);
hist(X(:),100)
% Create second subplot
ax(2) = subplot(212);
Now link the axes of the two subplots:
linkaxes(ax)
By plotting on the second subplot, the first one will adapt
imagesc(X)
First, you have the following:
Then:
Extending the example to images only:
load clown
figure
imagesc(X)
h(1) = gca;
I = imread('eight.tif');
figure
imagesc(I)
h(2) = gca;
Note that the configurations of the the first handle prevail:
linkaxes(h)
1.Get the handle of your figure and the axes, like this:
%perhaps the easiest way, if you have just this one figure:
myFigHandle=gcf;
myAxHandle=gca;
%if not possible, you have to search for the handles:
myFigHandle=findobj('PropertyName',PropertyValue,...)
%you have to know some property to identify it of course...
%same for the axes!
2.Set the properties, like this:
%set units to pixels (or whatever you prefer to make it easier to compare to the other plot)
set(myFigHandle, 'Units','pixels')
set(myAxHandle, 'Units','pixels')
%set the size:
set(myFigHandle,'Position',[x_0 y_0 width height]) %coordinates on screen!
%set the size of the axes:
set(myAxHandle,'Position',[x_0 y_0 width height]) %coordinates within the figure!
Ok, based on the answer of #Lucius Domitius Ahenoba here is what I came up with:
hgload('fig1.fig'); % figure whose axis properties I would like to copy
hgload('fig2.fig');
figHandles = get(0,'Children');
figHandles = sort(figHandles,1);
ax(1) = findobj(figHandles(1),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
ax(2) = findobj(figHandles(2),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
screen_pos1 = get(figHandles(1),'Position');
axis_pos1 = get(ax(1),'Position');
set(figHandles(2),'Position',screen_pos1);
set(ax(2),'Position',axis_pos1);
This is the 'before' result:
and this is the 'after' result:
Almost correct, except that the aspect ratios are still off. Does anybody know how to equalize everything related to the axes? (I realize that I'm not supposed to ask questions when posting answers, however adding the above as a comment was proving a little unwieldy!)

`imagesc` in MATLAB: paper size and `colorbar`

I am using imagesc in MATLAB to show an NxM matrix as an image, where the warmer is the color the higher is the value. By using the following command:
f = imagesc(points, [0 1]);
the matrix points is displayed. Nevertheless, a legend showing the coupling between colors and values is missing. I have found out that the command:
colorbar
can be used so as to display the requested legend. However, when printing the figure on PDF using the following lines of code:
set(gcf, 'PaperUnits', 'centimeters')
set(gcf,'PaperSize',[12 8]) % Set the paper size to the figure size
print('-dpdf',figurePath)
I encounter two problems:
The paper size is not set properly
The color bar is not showing on the PDF
How can I fix these problems?
Thanks in advance,
Eleanore.
I've found a solution in the state of the art, that uses the export_fig script (https://sites.google.com/site/oliverwoodford/software/export_fig).
The following code is needed:
set(gcf, 'Color', 'w'); % Change background color
set(gcf, 'Position', [100 100 700 500]) % Change figure dimensions
export_fig([figurePath '.pdf']) % Export the figure
I always export my figures to .eps and then use the epstopdf utility that comes with Ghostscript to convert for inclusion in a LaTeX document; this seems to solve the vast majority of issues.
Another way to do it is to use the export_fig script, but I see you've already discovered that.

Blurry label text in matlab plots

I'm having some matlab plots. when I save the plot and then put it in my word document and then save it as pdf file. I get the plot labels blurry and some letters is unclear ?!
plot(d1,S,'*');
title('Frequency','FontWeight','bold','FontSize',11);
xlabel('delta','FontWeight','bold','FontSize',11), ylabel('sigma','FontWeight','bold','FontSize',11);
why does that happened (got angry)?!
how can I fix it ?!
There are many discussions about this on the web, but non of the solutions actually satisfied me when I wanted to export a graph to an image.
Anyway here is what I've done:
MyFont = {'FontName', 'Times New Roman', 'FontSize', 25};
graph_size = [1200 800]; % in pixels
fig_h = figure('Units', 'pixels', 'Position', [10 50 graph_size]);
% Do your plot
x = 0:0.1:2*pi;
plot(x, sin(x))
set(gca, MyFont{:}); % Adjust all the font sizes in the axes
Now you can copy a vector-based version (which is nicest quality as #wakjah mentioned) to clipboard with print (as #Amro said):
print -dmeta
Or with hgexport which exports to metafile again:
hgexport(figH,'-clipboard')
However you need to adjust the graph_size and FontSize in MyFont manually to get your desired output. But the good thing is that if you want it for some publication you just need to do it once.
Please note that although you are exporting the graphs as a vector-based format but your graph lines would still seem fractured if you zoom on them but they are not blurry. This is why you might want to increase the size of your graph on screen (graph_size and consequently the FontSize) to have a more accurate graph.
Hope this helps.
Related posts:
MATLAB: print a figure to pdf as the figure shown in the MATLAB
In matlab, how do you save a figure as an image in the same way as using "Save As..." in the figure window?

MATLAB - How to avoid a jagged image?

How do I avoid a jagged image in MATLAB?
I have a 600 x 600 pixels image opened in MATLAB and do some processing on the image. However, when I save it, it looks so blurred and jagged. What should I do?
(This question is related to my previous question, MATLAB - How to plot x,y on an image and save?)
fid = fopen(datafile.txt);
A = textscan(fid,'%f%f%f'); %read data from the file
code = A{1};
xfix = A{2};
yfix = A{3};
for k=1:length(code)
imagefile=code(k);
rgb = imread([num2str(imagefile) '.jpg']);
imshow(rgb);
hold on;
x = xfix2(k);
y = yfix2(k);
plot(x,y,'-+ b'); % plot x,y on the
saveas(([num2str(imagefile) '.jpg'])) % Save the image with the same name as it open.
end
hold off
If it is just a resolution issue, perhaps using the print command (as listed below) with an explicit resolution option may fix it.
print(gcf,'-djpeg','-r600',[num2str(imagefile)])
My guess would be JPEG compression artifacts. JPEG isn't a great format for data with a lot of high frequency components. Have you tried turning the compression down? Like so:
imwrite(f.cdata,([num2str(imagefile) '.jpg']),'Quality',100);
The default for the quality parameter is only 75. That's plenty for a lot of cases, but you might need more.