Blurry label text in matlab plots - matlab

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?

Related

How to avoid marker clipping in Matlab while saving two axis figure to pdf?

I have some trouble while exporting a two axis figure with Matlab to pdf. The following example code works great while creating the figure in Matlab. But in the generated pdf-file all my red markers on the x-axis get cut off (see screenshot). Curiously this problem only occures, when I use a two axis plot
Here is a screenshot of my figure
fig = figure;
x = linspace(0,25);
y = sin(x/2);
marker = linspace(0,25,5);
yyaxis left
plot(x,y,'g');
hold on;
r = x.^2/2;
yyaxis right
plot(x,r,'b');
hold on;
plot(marker,0,'rx','Markersize', 8);
saveas(gcf,'myfigure.pdf');
Can anyone please help me out here?
I’ve come into this a handful of times, super frustrating. I’ve usually tried some of the below options, and eventually something works. Some things to try:
Print as a png, then convert to PDF with gimp or something of the like (where 300 represents 300 dpi):
print(handle, savefilename, ‘-dpng’, ‘-r300’)
Print as a vector image with the painters renderer, then convert to PDF with gimp:
print(handle, savefilename, ‘-depsc’, ‘-painters’)
Try changing the marker to a different shape, or size, or both (using for example: 'markersize', 3, 'marker', 's')
Good luck. Let us know what ends up fixing it!

Matlab figure -> Word -> PDF results in bad quality

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)

`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.

Export Matlab figure as PNG?

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.

how to make an image large enough to avoid tick label overlapping?

Assume that the data X has size 1000 *1000. X is displayed using the command:
imagesc(X);
and all the rows are labeld using:
set(gca, 'YTickLabel', somelabels);
Although the data X are properly polotted and the Ytick labels are also shown, the labels are highly overlapped because of the large number of rows. Is there any way to solve the problem? Any help will be highly appreciated.
Edit 1
I realize my question was not stated well to represent my problem. I am going to wrap up my understanding based on the answers and re-ask a question:
To show as many rows/labels in a Figure Window, the following helps:
set(gca,'FontSize',6),
or, alternate the distance (suggested by yuk),
or, set(gca,'YTick',1:10:1000,'YTickLabel',somelabels(1:10:1000));
The code
set(gca,'Units','pixels','Position',[20 20 10000 10000]);
will display a zoomed-in image by default. But if the zoomed-in image is too large to fit in the Figure Window, only part of the image will be displayed. However, neither zoom out nor the pan tool can reach to the rest part of that image.
The default behavior of the code
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
displays the whole image fitting to the Figure Window with overlapping labels. Nevertheless, it does allow one to zoom into part of the image and to see the un-overlapped labels.
If I save the image into a pdf file:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
saveas(gcf, 'fig.pdf');
Then the saved pdf is only the image fit to the Figure Window with overlapping labels. However, unlike zoom in within Matlab figure window, zoom in within a pdf reader won't change the relative position/distance of labels. As a result, the zoomed-in image in pdf is still label-overlaped.
So my question is:
How to save the image into a pdf file or png such that it has a similar behavior as of point 3 above when opened in Adobe reader, rather than that of point 4?
You can also play with axes label font to make it smaller.
set(gca,'FontSize',6)
See also other axes properties to change font - FontName, FontWidth, FontUnits, etc.
Another solution: If your labels are short, you can alternate there distance from the axes, so the labels will not overlap. Check this example:
lbl = cellstr(reshape(sprintf('%3d',1:100),3,100)');
lbl(1:2:100) = strcat(lbl(1:2:100),{' '});
imagesc(rand(100))
set(gca,'ytick',1:100)
set(gca,'yticklabel',lbl)
Part of the resulted image:
UPDATE
To answer your updated question.
PDF document can contain only static images. Once you saved the figure to PDF (or any other graphic file), you cannot zoom in/out as with MATLAB figure tools.
You can zoom first on the MATLAB figure, then save PDF file. In this case the figure will be saved as is. But this way assumes user interactivity with the figure.
If you know your region of interest in advance, you can set axes limits with XLim/YLim properties, then save the figure.
Example:
imagesc(X);
set(gca, 'ytick', 1:1000, 'yticklabe', ylabel);
set(gca, 'XLim',[1 20], 'YLim', [20 40])
saveas(gcf, 'fig.pdf');
By the way, you can also save figure to file with PRINT function. More flexible. SAVEAS is just wrapper around it.
print('-dpdf','fig.pdf')
Another option is to rotate the tick labels which is discussed in this technical solution. You can find a number of easy-to-use implementations on the MATLAB File Exchange.