Embedding matlab plot in pdf for printing: Sizes - image

I'm currently creating my figures in matlab to embed themvia latex into a pdf for later printing. I save the figures and save them via the script export_fig! Now I wonder which is the best way to go:
Which size of the matlab figure window to chose
Which -m option to take for the script? It will change the resolution and the size of the image...
I'm wondering about those points in regards to the following two points:
When chosing the figure-size bigger, there are more tickmarks shown and the single point markers are better visible
When using a small figure and using a big -m option, I still have only some tickmarks
When I generate a image which is quite huge (e.g. resolution 300 and still 2000*2000px) and than embed it into the document: Does this than look ugly? Will this be embedded in a nice scaling mode or is it the same ugliness as if you upload a 1000*1000px image onto a homepage and embed it via the widht and height tags in html -> the browser displays it quite ugly because the browser doesn't do a real resize. So it looks unsharp and ugly.
Thanks in advance!

The MATLAB plots are internally described as vector graphics, and PDF files are also described using vector graphics. Rendering the plot to a raster format is a bad idea, because you end up having to choose resolution and end up with bigger files.
Just save the plot to EPS format, which can be directly embedded into a PDF file using latex. I usually save my MATLAB plots for publication using:
saveas(gcf, 'plot.eps', 'epsc');
and embed them directly into my latex file using:
\includegraphics[width=0.7\linewidth]{plot.eps}
Then, you only need to choose the proportion of the line the image is to take (in this case, 70%).
Edit: IrfanView and others (XnView) don't display EPS very well. You can open them in Adobe Illustrator to get a better preview of what it looks like. I always insert my plots this way and they always look exactly the same in the PDF as in MATLAB.
One bonus you also get with EPS is that you can actually specify a font size so that the text is readable even when you resize the image in the document.
As for the number of ticks, you can look at the axes properties in the MATLAB documentation. In particular, the XTick and YTick properties are very useful manually controlling how many ticks appear no matter what the window resolution is.
Edit (again): If you render the image to a raster format (such as PNG), it is preferable to choose the exact same resolution as the one used in the document. Rendering a large image (by using a big window size) and making it small in the PDF will yield bad results mainly because the size of the text will scale directly with the size of the image. Rendering a small image will obviously make for a very bad effect because of stretching.
That is why you should use a vector image format. However, the default MATLAB settings for figures produce some of the same problems as raster images: text size is not specified as a font size and the number of ticks varies with the window size.
To produce optimal plots in the final render, follow the given steps:
Set the figure's font size to a decent setting (e.g. 11pt)
Render the plot
Decide on number of ticks to get a good effect and set the ticks manually
Render the image to color EPS
In MATLAB code, this should look somewhat like the following:
function [] = nice_figure ( render )
%
% invisible figure, good for batch renders.
f = figure('Visible', 'Off');
% make plots look nice in output PDF.
set(f, ...
'DefaultAxesFontSize', 11, ...
'DefaultAxesLineWidth', 0.7, ...
'DefaultLineLineWidth', 0.8, ...
'DefaultPatchLineWidth', 0.7);
% actual plot to render.
a = axes('Parent', f);
% show whatever it is we need to show.
render(a);
% save file.
saveas(f, 'plot.eps', 'epsc');
% collect garbarge.
close(f);
end
Then, you can draw some fancy plot using:
function [] = some_line_plot ( a )
%
% render data.
x = -3 : 0.001 : +3;
y = expm1(x) - x - x.^2;
plot(a, x, y, 'g:');
title('f(x)=e^x-1-x-x^2');
xlabel('x');
ylabel('f(x)');
% force use of 'n' ticks.
n = 5;
xlimit = get(a, 'XLim');
ylimit = get(a, 'YLim');
xticks = linspace(xlimit(1), xlimit(2), n);
yticks = linspace(ylimit(1), ylimit(2), n);
set(a, 'XTick', xticks);
set(a, 'YTick', yticks);
end
And render the final output using:
nice_figure(#some_line_plot);
With such code, you don't need to worry about the window size at all. Notice that I haven't even showed the window for you to play with its size. Using this code, I always get beautiful output and small EPS and PDF file sizes (much smaller than when using PNG).
The only thing this solution does not address is adding more ticks when the plot is made larger in the latex code, but that can't be done anyways.

Related

Matlab gui image incorrectly blue

I am creating a GUI containing an image using the following code:
try
Imagenamehere = imread('Imagenamehere.jpg');
axes(handles.Logo)
image(Imagenamehere)
set(gca,'xtick',[],'ytick',[])
catch
msgbox('Please download all contents from the zipped file into working directory.')
end
The image shows up but for some reason is completely coloured blue as if put through a blue filter. I don't think it would be wise to upload the image but it is a simple logo coloured black and white.
Anyone know what could be causing this?
Check the size, type (probably uint8) and range of your image. It sounds like for some reason your images are being displayed with colormap as jet (the default), and possibly also that your range is not what MATLAB expects (e.g. 0 to 1 not 0 to 255), resulting in all your values being relatively low (blue on the jet colormap).
"black and white" is just one way of interpreting an image file which contains only two colors. MATLAB makes several assumptions when you pass data into a display function like image. If you don't specify colormap and image data range, it will make a guess based off things like data type.
One possibility is that your logo file is an indexed image. In these cases you need to do:
[Imagenamehere map] = imread('Imagenamehere.jpg');
colormap(map);

Matplotlib Plots Lose Transparency When Saving as .ps/.eps

I'm having an issue with attempting to save some plots with transparent ellipsoids on them if I attempt to save them with .ps/.eps extensions.
Here's the plot saved as a .png:
If I choose to save it as a .ps/.eps here is what it looks like:
How I got around this, was to use ImageMagick to convert the original png to a ps. The only problem is that the image in png format is about 90k, and it becomes just under 4M after conversion. This is not good since I have a lot of these images, and it will take too much time to compile my latex document. Does anyone have a solution to this?
The problem is that eps does not support transparencies natively.
There are few options:
rasterize the image and embed in a eps file (like #Molly suggests) or exporting to pdf and converting with some external tool (like gs) (which usually relies as well on rasterization)
'mimic' transparency, giving a colour that looks like the transparent one on a given background.
I discussed this for sure once on the matplotlib mailing list, and I got the suggestion to rasterize, which is not feasible as you get either pixellized or huge figures. And they don't scale very nicely when put into, e.g., a publication.
I personally use the second approach, and although not ideal, I found it good enough. I wrote a small python script that implements the algorithm from this SO post to obtain a solid RGB representation of a colour with a give transparency
EDIT
In the specific case of your plot try to use the zorder keyword to order the parts plotted. Try to use zorder=10 for the blue ellipse, zorder=11 for the green and zorder=12 for the hexbins.
This way the blue should be below everything, then the green ellipse and finally the hexbins. And the plot should be readable also with solid colors. And if you like the shades of blue and green that you have in png, you can try to play with mimic_alpha.py.
EDIT 2
If you are 100% sure that you have to use eps, there are a couple of workarounds that come to my mind (and that are definitely uglier than your plot):
Just draw the ellipse borders on top of the hexbins.
Get centre and amplitude of each hexagon, (possibly discard all zero bins) and make a scatter plot using the same colour map as in hexbin and adjusting the marker size and shape as you like. You might want to redraw the ellipses borders on top of that
Another alternative would be to save them to pdf
savefig('myfigure.pdf')
That works with pdflatex, if that was the reason why you needed to use eps and not svg.
You can rasterize the figure before saving it to preserve transparency in the eps file:
ax.set_rasterized(True)
plt.savefig('rasterized_fig.eps')
I had the same problem. To avoid rasterizing, you can save the image as a pdf and then run (on unixish systems at least) in a terminal:
pdftops -eps my.pdf my.eps
Which gives a .eps file as output.
I solved this by:
1) adding a set_rasterization_zorder(1) when defining the figure area:
fxsize=16
fysize=8
f = figure(num=None, figsize=(fxsize, fysize), dpi=180, facecolor='w',
edgecolor='k')
plt.subplots_adjust(
left = (18/25.4)/fxsize,
bottom = (13/25.4)/fysize,
right = 1 - (8/25.4)/fxsize,
top = 1 - (8/25.4)/fysize)
subplots_adjust(hspace=0,wspace=0.1)
#f.suptitle('An overall title', size=20)
gs0 = gridspec.GridSpec(1, 2)
gs11 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs0[0])
ax110 = plt.Subplot(f, gs11[0,0])
f.add_subplot(ax110)
ax110.set_rasterization_zorder(1)
2) a zorder=0 in each alpha=anynumber in the plot:
ax110.scatter(xs1,ys1 , marker='o', color='gray' , s=1.5,zorder=0,alpha=0.3)#, label=label_bg)
and
3) finally a rasterized=True when saving:
P.savefig(str(PLOTFILENAME)+'.eps', rasterized=True)
Note that this may not work as expected with the transparent keyword to savefig because an RGBA colour with alpha<1 on transparent background will be rendered the same as the RGB colour with alpha=1.
As mentioned above, the best and easiest choice (if you do not want to loose resolution) is to rasterized the figure
f = plt.figure()
f.set_rasterized(True)
ax = f.add_subplot(111)
ax.set_rasterized(True)
f.savefig('figure_name.eps',rasterized=True,dpi=300)
This way, you can manage the size by dpi option as well. In fact, you can also play with the zorder below you want to apply the rasterization:
ax.set_rasterization_zorder(0)
Note: It is important to keep f.set_rasterized(True) when you use plt.subplot and plt.subplot2grid functions. Otherwise, label and tick area will not appear in the .eps file
My solution is to export the plot as .eps, load it up to Inkscape for example, then Ungroup the plot, select the object that I want to set the transparency and just edit the Opacity of the Fill in the "Fill and Stroke" tab.
You can save the file as .svg if you want to tweak it later, or export the image for a publication.
If you are writing the academic paper in latex, I would recommend you export the .pdf file rather than .eps. The .pdf format supports transparency perfectly and has good compression efficiency, and most importantly, can be easily edited in Adobe Illustrator.
If you wanna further edit the graph (NOT EDITING DATA! I MEAN, FOR GOOD-LOOKING), you could open the exported graph, in Adobe Acrobat - Edit - Copy elements into Adobe Illustrator. The two software can handle everything perfectly.
I work happily with this method. Everything clear, editable and small-size. Hope can help.

Manipulating subsections of an array

I am using R to plot trying to conditionally change parts of an array
based on the columns of the array.
I have worked out the following steps:
x<-array(1,dim=c(4,4,3))
r<-x[,,1]
g<-x[,,2]
b<-x[,,3]
r1<-apply(r[,2:3],1:2,function(f){return(0)})
g1<-apply(g[,2:3],1:2,function(f){return(0)})
b1<-apply(b[,2:3],1:2,function(f){return(0)})
r3<-cbind(r[,1],r1,r[,4])
g3<-cbind(g[,1],g1,g[,4])
b3<-cbind(b[,1],b1,b[,4])
# Pass to pixmapRGB
This works, but as I am new to R, I was wondering if
there was a more efficient way to manipulate parts
of an array.
For example, does apply know which element it is working on?
The bigger picture is that I want to graph a time-series scatter
plot over many pages.
I would like to have a thumbnail in the corner of the page that is
a graph of the whole series. I would like to color a portion of
that thumbnail a different color to indicate what range the
current page is examining.
There is alot of data, so it is not feasible to redraw a new plot
for the thumbnail on every page.
What I have done is to first write the thumbnail plot out to a tiff file.
Then I read the tiff file back in, used getChannels from pixmap
to break the picture into arrays, and used the above code to change
some of the pixels based on column.
Finally I then print the image to a viewport using
pixmapRGB/pixmapGrob/grid.draw
It seems like alot of steps. I would be grateful for any pointers
that would help me make this more efficient.
Maybe I don't understand your question, but if what you're trying to do is just "change some pixels based on column," why don't you just use the basic array indexing to do that?
This will do the same thing you have posted:
x<-array(1,dim=c(4,4,3))
r<-x[,,1]
g<-x[,,2]
b<-x[,,3]
r[,2:3]=0
g[,2:3]=0
b[,2:3]=0
Is that helpful?
Perhaps more of a comment than an answer, but when I try to plot over a number of pages I usually go left to right, breaking up the plots into quantiles and setting appropriate xlim (or ylim)
x <- rnorm(100000)
y <- rnorm(100000)
df <- data.frame(x,y)
seq1 <- quantile(df$x, probs = seq(0,1,0.1))
seq2 <- quantile(df$x, probs = seq(0,1,0.1))
for(x in 1:(length(seq1)-1)) {
plot(df, xlim=c(seq1[x],seq1[x+1]))
}
No idea how to overlay a thumbnail onto the graphs although I think you could do this with one of the rimage functions if you saved the thumbnail.
You could avoid having to read and paste a tiff thumbnail by actually replotting the whole chart at reduced scale. check out par(fig) , and then do something like
Rgames: plot(1:2,1:2)
Rgames: par(mar=c(.1,6,.1,.1),new=T,fig=c(0,.25,.5,.75))
Rgames: plot(1:2,1:2)
Rgames: polygon(c(1,2,2,1),c(1,1,2,2),col='red')
("Rgames:" is my prompt)
You'll have to play a bit with the margin values, but this will get your "mini-graph" set up.

setting density upon image read with RMagick

I am attempting to use RMagick to convert an SVG to a PNG of a different size.
When I read in the SVG with Magick::Image.read('drawing.svg') and write it out to drawing.png (the equivalent of just running convert drawing.svg drawing.png from the command line), the size is 744x1052.
Let's suppose I want the PNG to be twice as large as it is by default. You can't just read it in, resize it, then write it out, as that first rasterizes the SVG and then scales that image to be twice as large, losing quality and the entire benefit of using a vector graphic in the first place. So instead, if I understand correctly, you're supposed to set the image's density upon read.
image = Magick::Image.read('drawing.svg'){self.density = 144}.first
But image.density still reports the density as "72x72", and if I write out the image it has the same size as before, 744x1052. It doesn't seem to matter how I specify the density upon read. With 144, "144", 144.0, "144.0", "144x144", and "144.0x144.0", it always comes back "72x72".
Running convert -density 144 drawing.svg drawing.png from the command line works as expected and generates a PNG that's twice as large as before, 2104x1488.
I'm using OS X 10.6.7, ImageMagick 6.7.0-0 (installed via MacPorts), RMagick 2.13.1, and Ruby 1.9.2p180. When I put my code into the context of a little Sinatra webapp on Heroku, it has the same incorrect behavior, so the issue does not seem to lie with OS X or MacPorts.
Density is about resolution (i.e. dots per inch), not the rendered size. From the fine manual:
The vertical and horizontal resolution in pixels of the image. The default is "72x72".
I think you're looking for resize or resize!:
Changes the size of the receiver to the specified dimensions.
You can specify the new size in two ways. Either specify the new width and height explicitly, or specify a scale factor, a number that represents the percentage change.
So this will work:
Magick::Image.read('drawing.svg').first.resize(2).write('drawing.png')
Or this:
img = Magick::Image.read('drawing.svg').first
img.resize!(2)
img.write('drawing.png')
I don't know why convert behaves differently than the library, there could be other default settings in play that have different defaults in the library or maybe -density does more than set the density.
If resize isn't doing the trick for you (and, based on your comments, it is happening too late to be of use), you can try setting the size parameter in the block:
img = Magick::Image.read('drawing.svg'){ |opts| opts.size = '2104x1488' }.first
Of course, you have to know how big the SVG is before hand. You're supposed to be able to specify things like 200%x200% for the geometry but read always ignores the flag on the Magick::Geometry when I try it.

How to add image in MATLAB GUI?

I want to switch back and forth between two images, like blinking: 1 second for the first image and one second for second image.
I'm not totally sure of what you want to do (specifically what type of images you are trying to display), but here's some sample code that may do what you want:
image1 = imread('cameraman.tif'); % Load a test image
image2 = imread('circles.png'); % Load another test image
hAxes = gca; % Get a handle to the current axes
for iLoop = 1:5, % Loop five times
imshow(image1,'Parent',hAxes);
pause(1);
imshow(image2,'Parent',hAxes);
pause(1);
end
I used the general function IMSHOW, but this sometimes changes other properties of the figure/axes and that may not be to your liking (since you mention adding this to an existing GUI). You may want to use the IMAGE function instead. Also, instead of the for loop you could use a while loop that stops switching images when a condition is met (such as a button press).
How are your images stored in Matlab? As a matlab movie or a 3 or 4 dimensional matrix depending on if the images are color or grayscale. Also, if you have the image processing toolbox, implay and immovie. Another option assuming that your images are in a mxnx3xk (rgb color) or a mxnxk (gray scale) matrix. Then the following should work. Assuming the following
Img - matrix storing image data either with dimensions mxnx3xk
or mxnxk
handles.imageAxes -
handle for the axis you want to
display the image (set the tag of the
axis to imageAxes in GUIDE)
Now you can loop through Img
for i=1:k
% display the i^th image use `Img(:,:,i)` for a gray scale stack
image(Img(:,:,:,i),'parent',handles.imageAxes);
pause(1) % pause one second
end
that's it.

Resources