Printing figure at same size as figure window - matlab

I'm trying to save a figure in PDF format such that I don't get extraneous white space around it, i.e. the figure should be the same size as the figure window.
I'm pretty sure that the way to do it is
figureNames = {'a', 'b', 'c'};
for i = 1:3
set(figure(i), 'paperpositionmode', 'auto');
print(figure(i), '-dpdf', figureNames{i})
end
But it's not working. I'm getting as much white space as ever. Can someone enlighten me as to what's wrong?

You can try "all in one" solutions for converting figures to pdf-files. I use mlf2pdf
(http://www.mathworks.com/matlabcentral/fileexchange/28545) and it seems to work quite well. Moreover, the quality of the produced figures is much better due to Latex typesetting of everything

I've also had issues with this. The workaround is by printing in -depsc (color) or -deps if you just need grayscale figures. The encapsulated postscript file has practically no white margin. You can later convert the .eps file to pdf without trouble, if you working in LaTeX you can use it as it is.

It seems that setting PaperPositionMode to auto will get rid of extraneous white space for EPS files, but not PDF's.
To get rid of white space for PDF's, I wrote a little script to resize the paper to the figure size. Since it's so short, I've included it below in case anyone else needs it.
It is inspired by this document, as well as this StackOverflow question.
My solution works by manipulating only the paper size, not the figure axes, because manipulating the axes runs into trouble with subplots. This also means that some white space will remain. In MATLAB's vocabulary, the figures is bounded by its OuterPosition rather than TightInset.
function [filename] = printpdf(fig, name)
% printpdf Prints image in PDF format without tons of white space
% The width and height of the figure are found
% The paper is set to be the same width and height as the figure
% The figure's bottom left corner is lined up with
% the paper's bottom left corner
% Set figure and paper to use the same unit
set(fig, 'Units', 'centimeters')
set(fig, 'PaperUnits','centimeters');
% Position of figure is of form [left bottom width height]
% We only care about width and height
pos = get(fig,'Position');
% Set paper size to be same as figure size
set(fig, 'PaperSize', [pos(3) pos(4)]);
% Set figure to start at bottom left of paper
% This ensures that figure and paper will match up in size
set(fig, 'PaperPositionMode', 'manual');
set(fig, 'PaperPosition', [0 0 pos(3) pos(4)]);
% Print as pdf
print(fig, '-dpdf', name)
% Return full file name
filename = [name, '.pdf'];
end

Related

Replace pixels with symbols

I am trying to write a function that would take an indexed image as an input and will replace all its pixels by symbols or characters.
An image is worth more than a 1000 words: This is the desired look output. Each of the symbols represent an unique color value of the image.
My problem is that I don't know how to print in the screen the symbols in the correct place. My first approach has been to use the "Wingdings" font and to put text on the places, but does not work as expected. The text changes sizes when zoomed, and does not behave accordingly to the rest of the plot.
I leave here a small piece of code that creates a small grid and uses an example image.
function drawChars (img)
if nargin==0
load mandrill
img=X(1:4:end,1:4:end);
end
chars=randperm(numel(unique(img)));
[h,w]=size(img);
% Form a grid
figure
hold on
for ii=0:h
plot([ii ii],[0 w],'k');
end
for ii=0:w
plot([0 h],[ii ii],'k');
end
axis equal;
axis([0 h 0 w])
%% This does not work as expected
for ii=1:h
for jj=1:w
text(ii, jj, char(chars(img(ii,jj))), 'fontname', 'Wingdings', 'fontsize',10);
end
end
end
Short question: What approach would you use to solve the problem?
NOTE: there is a problem with the choice of chars also, but ignore it for the time being (if char { is chosen does not work nicely)
With figure changed to f=figure
r=size(img).*16;
set(f,'paperunits','points')
set(f,'papersize',r)
set(f,'paperposition',[0 0 r]);
print(f,'example.png','-dpng');
Prints the created figure to a png of sufficient size.

Axis commands changes TightInset property to zero

I use some things from this question get-rid-of-the-white-space-around-matlab-figures-pdf-output to get rid of the white space when saving figure plots and images. This works fine, but my problem is when I use commands like "axis square" or "axis image". Ivt sets TightInset property of corresponding axes to 0 in "y" direction. I mean when I use this:
inset=get(a,'TightInset');
second and fourth numbers in "inset" are always zero, even if I set title and x-label. So in the end I don't see plot titles and x-labels.
Can I fix it somehow? So far I do it manually by adding some suitable number, but it is not convenient.
EDIT: Some more code for example. It displays two histograms.
h=figure;
subplot(121)
bar(bins,histogram1,'hist');
axis square
title('Historgram 1');
xlabel('Intensity');
ylabel('Pixel count');
set(gca,'xlim',[0 1])
subplot(122)
bar(bins,histogram_out,'hist');
axis square
title('Histogram 2');
set(gca,'xlim',[0 1])
xlabel('Intensity');
ylabel('Pixel count');
and if I call
a=get(h,'Children');
for i=1:length(a)
inset=get(a(i),'TightInset');
%...some stuff here
end
those y-related numbers in inset are zeros. If I comment axis square and do this, then inset are correct and it does what I need.
As far as I know when you use 'TightInset' you'll get only the graph or image, axis will be removed. I downloaded a function from mathworks file exchange 'saveTightfigure.m' to solve a similar problem. But I did not needed axes. If you need axes may be you can edit limits set inside the function. I mean you can give a little more space at left and bottom for keeping the axes.

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?

When saving a figure as eps file, Matlab cuts off colormap labels

I have a figure generated using contourf with a colorbar. Most of my plots are fine, but when the values on the colorbar are of the order 10^{-3}, either the numbers 0.005 etc are written by the colorbar, or x10^{-3} is written at the top.
In both cases, part of the label gets cut off - either the 3 in x10^{-3} or half of the 5 in 0.005.
I can fix this using
set(gca, 'ActivePositionProperty', 'OuterPosition')
for the figure onscreen, but I need to save it in eps format. When I do this, the 3 (or 5) is cut off again!
I can also fix this if I manually pull the bottom right corner of the figure window to make it larger. But this changes the sizes of the axis labels etc in comparison to the plot itself so that they're different to all my other figures, i.e. the figures that I don't resize.
Any suggestions?
Matlab uses two sizes for figures: screen size (Position figure property) and the PaperSize. The former is used for displaying on screen, and the latter for printing or exporting to image formats other than .fig. I suspect this is the source of your problem.
Here is what you can try:
size = get(gcf,'Position');
size = size(3:4); % the last two elements are width and height of the figure
set(gcf,'PaperUnit','points'); % unit for the property PaperSize
set(gcf,'PaperSize',size);
This sets the size of the "paper" to export to .eps to the size of the figure displayed on screen.
If this doesn't work, you can try to play a bit with PaperSize or other "paper" related properties. The Figure Properties documentation page gives more info about properties.
Hope this helps!
The former suggestion is partly correct. Here is what i did:
set both, figure and paper units, to the same measure (figure has pixels, not points!)
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
do the same as suggested before:
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
the thing now is, that it might be shifted off the paper, as in my case, so put it back on
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
I am not sure about the offset of [0,0], but what is a single point cut off :)
Try this to save your file to filename.eps:
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
print(gcf,'filename','-depsc','-loose'); % Save figure as .eps file

In matlab, how can I zoom in on a plot in my script

I'd like to zoom in on a plot using a script. I'm only interested in horizontally constrained zooming. So I'd like to do something like
p = plot(myData);
z = zoom;
set(z, 'ZoomInToPoints' , [50 100]);
or
p = plot(myData);
myZoom([50, 100]);
So either of these functions would zoom into a plot like when you zoom in with the magnifying glass tool. I only specify two points because I only want to zoom horizontally.
Note, I've already tried to use xlim for this. While it works, it doesn't let me use the command text on my plots, which I need.
Calls to text will fix the text at a specific set of coordinates on the graph. Have you tried updating these after calling xlim?
EDIT: You can always adjust the text position:
x=1:.1:10;
y=sin(.1*x);
plot(x,y)
text(6,.8,'test') %#Sample figure
F=get(0,'children'); %#Figure handle
A=get(F,'Children'); %#Axes handle
T=findobj(A,'Type','text'); %# Text handle
oldxlim=xlim; %#grab the original x limits before zoom
oldpos=get(T,'Position'); %#get the old text position
set(A,'xlim',[5 15]); %#Adjust axes
newxlim=xlim;
newpos=[(oldpos(1)-oldxlim(1))*(diff(newxlim))...
/(diff(oldxlim))+newxlim(1) oldpos(2:end)];
%#interpolate to place the text at the same spot in the axes
set(T,'Position',newpos) %#Finally reset the text position
Not pretty, but it should work. If you have more than one annotation per axes or axes per figure, you can always throw the above code in a loop.
What is the problem with text and xlim? Is this not the type of behavior you want?
plot(1:100,randn(100,1))
text(80,1.5,'text')
set(gca,'XLim',[70 100]) % notice that text stays at same point in "data space" but moves in "axis space"
text(80,1,'text2'); % new text appears in axis space as well
If I'm misunderstanding and you want text to appear at a specific point in your axis space (not the data space that text uses) regardless of how zoomed in you are, you can create another set of axes for your text:
inset_h = axes('position',[0.5 0.5 0.2 0.2])
set(inset_h,'Color','none'); axis off
text(0,0,'text')