I need to automatically export figures from Matlab to PNG. My figure has a size of 600x200 px:
hFig = figure(1);
set(hFig, 'Color', [1 1 1]); % backgroundcolor white
set(hFig, 'Position', [500 500 600 200]) % size 600x200
I tried e.g.
print -dpng image.png
but the image.png is larger than 600x200 px. Exporting the figure manually from the Figure Window GUI using the "save" button works great, I want to do exactly this automatically / from a script. Thanks for any hint!
I also know the problem that figures save never look the same as on screen.
There is the saveas command which might work for you - but does also some resolution changing for me.
Only way I know is to carefully set every aspect like this:
set(gcf,'PaperUnits','inches','PaperSize',[2,6],'PaperPosition',[0 0 2 6])
print('-dpng','-r100','test')
(so paper size is 2x6" and print with 100dpi, PaperPosition is important as you will have otherwise some extra border.)
My preferred approach for generating png plots from MATLAB is the export_fig utility available at the MATLAB file exchange.
Here's an example:
set(gcf, 'Position', [100 100 500 500], 'Color', 'w')
x=0:0.01:10;
plot(x, sin(x))
set(gca, 'FontSize', 20, 'FontName', 'Arial')
export_fig 'strip-diff-far-forward.png' -painters -nocrop
This will create a png that is 500 x 500 pixels, with 20 pixel fonts. I'm sure that internally it does the same kinds of things as in bdecaf's answer, but it is all ecapsulated in a function for you already, and has a bunch of other features too.
The drawback is that if you use the -painters renderer (which I think looks the best) you will need to have ghostscript installed. If you don't want to mess with that, you can change -painters to -opengl
Edit Now setting figure size correctly!
Based upon bdecaf's answer:
set(gcf,'PaperUnits','inches','PaperSize',[600/96,200/96],'PaperPosition',[0 0 600/96 200/96])
print('-dpng','-r96','test')
96 is the dpi of my system. This gives me EXACTLY the same output as the save function. For Windows the dpi is typically 96, sometimes 120. Simply adjust it accordingly to your system. Note that on a beamer the DPI might again be different from your system, especially if your system has 120 DPI! 96 DPI should in general be a quite safe choice for beamers I think. Google if you need help finding out the DPI setting of your system. This answer is 99,9% based on bdecaf and Florian, so I will leave bdecaf's answer selected as the right one.
edit: 600 = horizontal image size in px, 200 = vertical image size in px
Amro answer works perfectly, after you generate your figure, set PaperPositionMode to auto and the print size will be the same as screen size.
set(gcf, 'PaperPositionMode','auto')
print('-dpng','test.png')
Try:
set(hFig, 'PaperPositionMode','auto') %# WYSIWYG
print -dpng -r0 image.png %# at screen resolution
This tells it to produce an image the same size as it appears on screen.
Related
I know there are lots of questions on matlab printing questions, but I can't seem to figure this out.
I want to print/save my figure at 17x23cm printed. With a resolution of 600dpi.
I've tried this
set(gcf, 'Units', 'centimeters', 'Position', [0 0 17 23], 'PaperUnits', 'centimeters', 'PaperSize', [17 23]);
I'm then using the export_fig script and do either of the following
export_fig Test.pdf -pdf -transparent;
export_fig Test.pdf -pdf -transparent -r600;
Either way, I get a figure that is ~14x19 cm. And the resolution is only 100dpi.
So I thought, okay 600dpi for a 17cm figure is ~4,000 pixels. So lets just set the figure on screen to be that many pixels
set(gcf, 'Units', 'pixels', 'Position', [0 0 4000 5500]);
But that doesn't work. I assume because my monitor isn't big enough to support that many pixels, so it won't display. And I can't then save it because the figure doesn't even show up.
I know I can resize after in gimp or illustrator or whatever. But I don't really want to.
How do I export/save a pdf/eps graph at a specific print size (17cm) with a specific resolution (600dpi)?
Printing using export_fig is going to crop the resulting figure to remove any white space (places where your figure has no content). Because of this, the output is going to be smaller than the Position that you specify.
To prevent this, you can use the -nocrop option.
export_fig('Test.pdf', '-pdf', '-nocrop', '-transparent', '-r600')
Specifying a resolution is really only intended to have an effect for raster images, for vector graphic formats such as PDF this shouldn't really have an effect. How are you determining the "resolution" of the PDF?
Another option is to just use the built-in print function to create your image
print('myimage.pdf', '-dpdf', '-loose', '-r600')
The -loose option here will ensure that it uses a loose bounding box and won't crop the empty regions of your figure, resulting in an image of the dimensions you're prescribing.
I am using a script to get an automated data treatment (polynomial interpolation, tangent, ...), but when I use the function set to change my plot options before saving, I don't always get the right result : only the font option (see code) seem to work, while the image is really small and the background color doesn't change as it should.
What I would like is to have both eps and jpg files with the plot options I used. Writing this script, I kept adding/moving plot options, and I really don't understand why sometimes some options appear on the plot but seem to be ignored while saving.
Here is the part of my code that has all the plot options, I added those three first line instead of all my treatment.
t=linspace(0,10,10);
front=rand(1,10);
fit=front+rand(1,10)/2;
degre=1;
plot(t,fit,'-b','LineWidth',2);
hold on
grid on
plot(t,front,'.r','LineWidth',2);
hold off
l=legend({['Interpolation polynomiale de degre ',num2str(degre)],'Resultats experimentaux'});
set(l,'Color',[0.8 0.8 0.8])
set(gca,'FontSize',12,'FontWeight','bold','Color',[0.8 0.8 0.8]);
set(gcf, 'Units', 'pixels', 'Position', [0, 0, 1200, 1000])
xlabel('\fontsize{14}Temps de maintien (en s)')
ylabel('\fontsize{14}Distance parcourue (en mm)');
str='essai';
title(str)
filename='essai1';
saveas(gcf,filename,'jpg')
saveas(gcf,filename,'epsc2')
Trying to fix the resolution issue, I tried to change the default resolution using set(0, 'DefaultFigurePosition', [0 0 1200 1000]); but this line of code does not change anything
Thank you in advance
The background of the saved image will be white unless you set InvertHardcopy to off and for the size try 'PaperPositionMode'
set(gcf,'InvertHardcopy','off');
set(gcf,'PaperPositionMode','auto');
set(gcf,'Position', [0, 0, 2400, 2000]); %the resoultion you want
I managed to solve both issues on my example script, using
hFig = figure(1);
set(hFig, 'Position', [0 0 1200 1000])
before "plot", and
l=legend({['Interpolation polynomiale de degre ',num2str(degre)],'Resultats experimentaux'});
set(l,'Color',[0.8 0.8 0.8])
set(gca,'FontSize',12,'FontWeight','bold','Color',[0.8 0.8 0.8]);
set(gcf,'InvertHardcopy','off');
between plot and plot options.
However, this does not work with my main code, I am trying to put in comment most of my non-vital plot options and see what happens.
It would be great if someone could provide me with a better understanding of how those options work, I am mostly coding by try-and-error, but this is not the most efficient approach.
Edit I solved my problem, I had 4 plots on the same figure and I just wrote hold all instead of hold on
Looking at Matlab help, this shouldn't work, but it did.
hold all is the same as hold on.
Note: This syntax will be removed in a future release. Use hold on instead.
If anyone has an explanation as to why it worked, I would like to understand what happened.
Thank you
I create some figures with matlab and export them by using the "Edit -> Copy Figure" with setting "Preserve information (metafile if possible)". I import this in Word 2010. However, if I convert the word document with "save as pdf" the figures have artifacts.
The following image gives you an impression. To the left is Word at 400% zoom, to the right is the pdf with 400% zoom. One can clearly see that dotted lines become straight lines etc. How can I avoid this?
Expanding a bit on the answer that am304 gave - I just tested the following:
figure
% create a plot with some fine detail:
plot(sin(1./linspace(0.02, 1, 1000)));
% set the "paper size" of the figure (not the size on screen) to 30x20 cm:
set(gcf, 'PaperUnits', 'centimeters', 'PaperPosition', [0 0 30 20]);
% "print" to png with a resolution of 300 dpi
print('-dpng', 'myplot.png', '-r300');
This results in the following picture being saved to disk (cropped to show just detail):
The full size picture is just 43 kB - but it is a very high resolution (300 dpi) rendering so you can see the fine details of the plot.
I can insert this picture into a Word document and save it as a pdf. When I then take a screen shot of the pdf, it looks like this:
As you can see - the detail is pretty much all there.
You can use the print function to export your figure to various formats. EPS or TIFF should give good results. I wouldn't use the "Edit -> Copy Figure" if you want high quality figures.
I used the comments here to create my own approach (also with help of: How to set the plot in matlab to a specific size?). So here is my function:
function figureprint(hFig, width, height, res, filename)
%# figure size printed on paper
set(hFig, 'PaperUnits','centimeters')
set(hFig, 'PaperSize',[width height])
set(hFig, 'PaperPosition',[0 0 width height])
set(hFig, 'PaperOrientation','portrait')
%# export
print(hFig, '-dpng', res, filename)
This function is printing a figure to a specific size in cm. E.g.
figureprint(hFig, 12, 10, '-r1500', 'testPng.png')
So "hFig" is saved as a *.png with a width of 12cm and a height of 10cm. I measured this and this works fine. Optimizations are of course possible.
If you use
set(gca,'LooseInset', get(gca,'TightInset'))
the exponent of the multiply factor for the y values is cutted (when big numbers are plotted) (see image). In this cases you have to modify the values, e.g. like this:
tight = get(gca,'TightInset');
tight(1,4) = 0.08;
set(gca,'LooseInset',tight)
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.
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?