rmarkdown vector graphics for knit word - knitr

When using rmarkdown with knitr in Rstudio to knit a Microsoft Word document, the graphics generally look crappy because the usual vector graphics formats, such as PDF are not supported in Microsoft Word.
Fortunately, the devEMF package in R generates the microsoft vector format EMF, and I almost have this working for my rmarkdown application. The problem is that my image is showing up way too small. How can I control the image size?
I've tried the standard things below:
---
title: "Plot size trouble demo"
author: "for stackoverflow"
output: word_document
---
Here I include graphics in a word document using the `emf` printing device.
```{r dev = 'emf', fig.ext = 'emf'}
require(devEMF)
plot(1:10, 1:10)
```
The plot is small, so I try to make it bigger with the `fig.height` and fig.width` options:
```{r dev='emf', fig.ext='emf', fig.height=10, fig.width=10}
require(devEMF)
plot(1:10, 1:10)
```
The plot region stayed the same size, and now I have super-small labels and points!
Finally, I try to use the `out.width` and `out.height` options to rescale the figure to a different size, but this produces nothing at all:
```{r dev='emf', fig.ext='emf', fig.height=10, fig.width=10, out.width = '5in', out.height= '5in'}
require(devEMF)
plot(1:10, 1:10)
```
Update: I noticed here that rmarkdown supports win.metafile, but the following also produces nothing:
```{r dev = 'win.metafile', out.width = '5in', out.height= '5in'}
plot(1:10, 1:10)
```

Related

Fix extra space in MATLAB's title plot

I'm writting the results for my thesis, this includes the generation of figures for my LaTeX document by using MATLAB code. I do this by making a figure of the data, and then I use the print command to save in an EPS file.
The problem is that the plot in the MATLAB window is correct as you can see here:
But when I compile my document in LaTeX (Lyx), the result is this:
.
As you can see, I have an unexpected big extra space in "iLm" title. The same occurs when I use LaTeX code in the label of different signals.
Searching in the web I tried the following command:
set(groot,'DefaultTextInterpreter','latex');
But just prints "iL_m" like I wrote in the code. How can I make the spacing consistent in the EPS file?
Here's the code I'm using:
clear h n
figure(1)
h(1) = plot(iLmVal.time,iLmVal.data(:,2),'LineWidth',1,'color','k','DisplayName','Modelo');
hold on
h(2) = plot(iLmVal.time,iLmVal.data(:,4),'LineWidth',1,'color','r','DisplayName','Circuito');
legend(h,'Location','southeast'),...
axis([0 0.06 -18 27]),title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times-Roman'),...
set(gca,'Color','white');
set(gca,'XTick',0:0.005:0.06),...
set(gca,'XTickLabel',0:5:60,'FontSize',20,'FontName', 'Times-Roman','XMinorGrid','on'),...
xlabel('Tiempo [ms]','FontSize',20,'FontName', 'Times-Roman'),...
set(gca,'YTick',-18:4:28),...
set(gca,'YTickLabel',-18:4:28,'FontSize',20,'FontName', 'Times-Roman','YMinorGrid','on'),...
ylabel('Corriente [A]','FontSize',20,'FontName', 'Times-Roman'),...
n = gca;
n.YAxis.MinorTick = 'on'; n.YAxis.MinorTickValues = -18:1:28;
n.XAxis.MinorTick = 'on'; n.XAxis.MinorTickValues = 0:0.0025:0.07;
grid on; hold off
I'm using MATLAB R2018a and Lyx 2.3.2-2. Also, by printing in PNG this problem doesn't occur, but the quality and resolution is very poor.
I don't think this is related to LyX, you should see this issue in the exported EPS file. You can fix this using a different font.
As you can see in the appearance of the figure in MATLAB, where the title is shown using a sans-serif font (definitely not 'Times-Roman'), MATLAB does not recognize the 'Times-Roman' font, and uses an alternative for rendering. This alternative font is used to determine the location of the subscript, which is positioned independently of the main text by MATLAB. However, this font name is written to the EPS file. When rendering the EPS file in a different program, the 'Times-Roman' font is recognized and used to render the text. Because this font has different metrics to the one used by MATLAB, the location of subscripts is not correct.
When printing to PNG, MATLAB creates a bitmap, therefore this problem does not occur.
On my computer (macOS), the fooling produce a correct representation on screen:
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times-Roman')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','TimesRoman')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times New Roman')
The following doesn't:
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times Roman')
On different computers, different font names will be available. Use a name that is recognized on your computer. Your best bet is 'Times', which is the PostScript name for this font and should be recognized everywhere.
Alternatively, use the export_fig utility on the File Exchange. This is a great tool for exporting MATLAB figures to EPS. It will not only fix your fonts, but make many other little tweaks that will improve the look of your figures.

Difference between print/saveas and export

I'm doing some plots in Matlab, but when exporting to pdf I'm not getting the same results I see on my screen. In particular, I'm trying to put white edges to the legend.
leg1 = legend(names);
set(leg1,'EdgeColor',[1 1 1]);
When using "File -> Save As -> Out.pdf" the edges are white, but when I use saveas(gca,'Out.pdf') or print -dpdf Out.pdf the edges are black. What is Matlab doing when I use the export function? How can I have the same results from the command line?
Edit
Just to be clear, this is an example code:
plot(rand(10,1))
leg1 = legend('Data');
set(leg1,'EdgeColor',[1 1 1]);
print -dpdf Out.pdf
The pdf file shows this:
Which clearly is not the intended figure, and its different from the one showed by Matlab. When I use the "File -> Save as" option, the edge of the label is displayed correctly.
When saving from the "File -> Save As " it runs an mfile filemenufcn.
You can call it diretly from the commandline:
filemenufcn ( figHandle, 'FileSaveAs' )
Its a shame Mathworks don't allow you to pass in a filename to save directly...
You can investigate that function to see what the function is doing to the figure before its being saved.
FYI: In the latest Matlab (R2015a) the final code that does the actual saving to pdf is hgexport. (Which is a p-code file but it does have some basic help) You could directly invoke that at the commandline.
You should also look at export_fig which is an excellent tool for exporting graphics to file.
I am afraid that the other answer does not really answer the question. This is how you "print" white line/text to a file: run
set(gcf, 'InvertHardCopy', 'off');
before using the print command.
However, for your specific case, since you are just trying to hide the box borders, the better way to do it is
legend boxoff
or
legend('boxoff')
Source: https://www.mathworks.com/matlabcentral/answers/102484-why-does-my-white-text-become-black-in-my-figure-when-printing-to-an-emf-file-in-matlab-7-5-r2007b

How to Control Margin of R Plot in Sweave Using Eclipse with Yap (.dvi)?

I'm having an issue with TeXlipse where I'm generating a plot in Eclipse via Sweave, and the TeX file seems to be jamming all of my PDF plots in the left most corner of the page. This is driving me crazy. I'm not sure what SweaveOpts might fix this, but \oddsidemargin, \evensidemargin, \begin{centering}, and \SweaveOpts{width=x, height=y} does not help. My code is below:
Sweave Code:
\documentclass{article}
\usepackage{Sweave}
\usepackage{graphicx}
\SweaveOpts{prefix.string=C:/SweavePlots/bar}
\DeclareGraphicsExtensions{.pdf}
...
\begin{figure}
\begin{center}
<<figname, fig=TRUE, include=TRUE, echo=FALSE>>=
plot(1:10)
#
\caption{I hope this Works}
\end{center}
\end{figure}
TeX Code:
\begin{figure}
\begin{center}
\includegraphics{C:/SweavePlots/bar-figname}
\caption{I hope this Works}
\end{center}
\end{figure}
Resultant Figure:
I found out that since the more recent versions of R only produce PDFs and I'm trying to use DVI, I need to explicitly set \SweaveOpts{eps=true}. The bottom line is that PDF images just don't get along well with DVI viewers like Yap. My successful code is as follows:
%
\documentclass{article}
\usepackage{Sweave}
\usepackage{graphicx}
\SweaveOpts{prefix.string=C:/SweavePlots/bar}
\SweaveOpts{eps=true}
\DeclareGraphicsExtensions{.eps}
\title{SweavePlotWithEPS}
\author{user992432}
\begin{document}
\maketitle
\begin{figure}
\begin{center}
<<figname, fig=TRUE, include=TRUE, echo=FALSE>>=
plot(1:10)
#
\caption{I hope this Works}
\label{fig:one}
\end{center}
\end{figure}
\end{document}

How to improve the quality (smoothness) of lines in contourplots Matlab's

How the line smoothness in a contour plot can be improved for publications? For instance, the dotted lines look really bad, the continuous lines look as if their thickness varies. See below
Here's part of the code:
Vals = [0:5:200]; contourf(X,Y,W,Vals,'EdgeColor','k','LineWidth',1.2,'LineStyle',':');axis square;grid;hold on
Vals = [10:10:200]; contour(X,Y,W,Vals,'EdgeColor','k','LineWidth',1.2);
Vals = [20 : 20 : 200]; [C,h] = contour(X,Y,W,Vals,'Color','k','LineWidth',1.8);
clabel(C,h,'FontName','Palatino Linotype','FontAngle','italic','Fontsize',9,'Color','w')
print -djpeg -r300 filename
Thanks!
Saved as png doesn't help much... check the lines :/ See below:
Check the dotted lines now...
Here's saving as eps (-r1200)... it looks better
Exporting as vector graphics will definitely improve the image over what you see on your screen; I use LaTeX for publications and you can either export to eps for postscript output, and use epstopdf for PDF output, and embed these directly in your document; that would be the best solution.
Additionally, there are also a bunch of general utilities for making your plots look better for camera-ready publications, the most notable that comes to mind is exportfig, which has a load of features to help even with pixel graphics. These go above and beyond just generating smoother-looking images.
http://www.mathworks.us/matlabcentral/fileexchange/23629-exportfig
(copied from that page):
This function saves a figure or single axes to one or more vector and/or bitmap file formats, and/or outputs a rasterized version to the workspace, with the following properties:
Figure/axes reproduced as it appears on screen
Cropped borders (optional)
Embedded fonts (pdf only)
Improved line and grid line styles
Anti-aliased graphics (bitmap formats)
Render images at native resolution (optional for bitmap formats)
Transparent background supported (pdf, eps, png)
Semi-transparent patch objects supported (png only)
RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
Variable image compression, including lossless (pdf, eps, jpg)
Optionally append to file (pdf, tiff)
Vector formats: pdf, eps
Bitmap formats: png, tiff, jpg, bmp, export to workspace
This function is especially suited to exporting figures for use in publications and presentations, because of the high quality and portability of media produced.
Update: I see your example code now. Did you try changing -r300 to some really high value? More pixels per inch should make everything look smoother. For publication, crank it up really high, like -r1200.
Original:
One thing you can try is exporting the plot in some format that supports vector graphics. Matlab supports both PDF and EMF, so try one of those. Export using the saveas command or from the figure's "File -> Save as" menu item. After that, open or import the image file in some other application and hopefully it will look better.
Please add a new screenshot if you get a nicer image!

How to export non-blurry eps images?

I'm exporting an image in Matlab using the eps format, but it smooths the image. Matlab does not blur the image using other formats such as png. I would like to know how to export a non-blurry image with eps format. Here is the resulting image using png:
And here is the resulting image using eps:
UPDATE:
The problem is reproducible on a Mac, and the issue is with the eps renderer rather than MATLAB. For e.g., saving imagesc(rand(20)) and viewing with Preview and GSview results in the following:
Preview screenshot
GSview screenshot
Clearly, the information is not lost. It is just not interpreted/read correctly by some EPS viewers. The solution is simple: use GSview to view your eps images. You can download it from here
On Macs especially, if your end application is latex/pdflatex, you will have to explicitly set it to use GS/GSview, because otherwise, it will default to the Quartz engine, which is baked into the OS.
PREVIOUS ANSWER:
I am unable to reproduce the behavior your described. Here is the code I used, tested using R2010b on WinXP 32-bit:
M = fspecial('gaussian',[20 20],5);
imagesc(M)
print('-dpng','a.png')
print('-depsc2','b.eps')
a.png
b.eps
Perhaps this is an issue with your EPS viewer...
not sure why it works but you can try doing the following:
eps2eps oldfile newfile
does the trick for me (on a mac os)
At first I thought you were doing something incorrectly, but then I remembered that this was an issue that was bothering the hell out of me a year or so ago. I couldn't come up with a way to "fix" this behaviour and from what I've researched, this is most likely a bug and several others have had this problem too and there is no known solution. Of course, I could be wrong about the last part and there might be solutions out there that have come out since I looked for them.
Any way, my workaround this problem was to use pcolor with shading flat instead of imagesc. When you export this to an eps format it preserves the image correctly. Example:
pcolor(rand(20));
shading flat
print('-depsc','figure.eps')
NOTE: You might see the appearance of thin, faint white lines along the anti-diagonals of each little square (depends on the OS & viewer). These are the edges of the graphics primitives that are used to render the image. However, this is not a flaw in MATLAB's export, but rather a fault in rendering in your EPS/PDF viewer. For e.g., with the default settings in Preview on my mac, these lines show up, whereas with the default in Adobe Reader 9.4, they don't appear.
If anyone is still interested in a workaround: Open the .eps-file with text editor and search for "interpolate". You'll probably find "/Interpolate true def" two or three times. Replace "true" with "false" and be happy :)
A note regarding Yoda's answer: in Preview in Mac OS X, you can make the thin white diagonal lines across each of the squares disappear by unchecking "Anti-alias text and screen art". Of course, the downside is that then any text (e.g. figure axes, etc) is not anti-aliased. Unfortunately, unchecking that has no effect on blurriness if you're using imagesc.
Another note is that if you use preview to make a pdf from your eps, the resulting pdf still displays correctly (non-blurry) when you open it in Acrobat.
I've been long struggling with this problem as well. So far, GSView is the only viewer I've found that displays the eps figures produced by Matlab (R2015b) correctly. eps2eps did not work for me (psutils 1.23).
The following eventually worked for me:
Export the figure to pdf, following the instructions here
pdf2ps file.pdf file.eps
I just wrote this simple drop-in replacement for imagesc. It doesn't support all but the most basic features, but I still hope it helps.
function h = imagesc4pdf(C)
[ny nx] = size(C);
px = bsxfun(#plus, [-0.5; 0.5; 0.5; -0.5], reshape(1:nx, [1 1 nx]));
py = bsxfun(#plus, [-0.5; -0.5; 0.5; 0.5], 1:ny);
n = numel(C);
px = reshape(repmat(px, [1 ny 1]), 4, n);
py = reshape(repmat(py, [1 1 nx]), 4, n);
h = patch(px, py, reshape(C,1,n), 'linestyle', 'none');
xlim([.5 nx+.5]);
ylim([.5 ny+.5]);
set(gca, 'ydir', 'reverse');
Apply opengl renderer to the figure
figure(gcf);
set(gcf,'renderer','opengl');
The blurring actually depends on the rendering software your viewer application or printer uses. To get good results all the time, make each pixel in your image an 8x8 block of pixels of the same color, i.e. resize the image like this:
im2 = imresize(im1, 8, 'nearest');
The blurring then only affects the pixels at the edge of each block. 8x8 blocks are best as they compress without nasty artifacts using DCT compression (sometimes used in eps files).
This page helped me a lot: http://tech.mof-mof.co.jp/blog/machine-learning-octave.html (written in Japanese, please use google translate for it)
And this is also helpful: Octave-Gnuplot-AquaTerm error: set terminal aqua enhanced title "Figure 1"...unknown terminal type"
I also answered at https://www.coursera.org/learn/machine-learning/discussions/weeks/2/threads/Dh-aRfqSEeaHSQ6l4xnh6g.
I reinstalled gnuplot like this:
$ brew cask install xquartz
$ brew cask install aquaterm
$ brew uninstall gnuplot
$ brew install gnuplot --with-aquaterm --with-x11 --with-qt # you can show other options by `$ brew options gnuplot`
You may edit ~/.octaverc like this:
setenv("GNUTERM", "qt")
and in octave window, after typing "system gnuplot", then
set pm3d interpolate 2, 2
After saving the file, open octave-cli.app, and type
imagesc(magic(3)), colorbar
I got this.