Saving plots as EMF files - r

I am having an issue with the emf() function from the devEMF package.
The code I am using -
library(devEMF)
emf(file = "trial.emf")
plot(1:10, seq(10, 100, 10), type = "l", xlab = "Time", ylab = "Distance")
#sample plot
dev.off()
This does not have the plot line but does have everything else (labels, axis ticks, title).
Am I missing some graphics package?
sessionInfo()
#R version 3.3.2 (2016-10-31)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 7 x64 (build 7601) Service Pack 1
#locale:
#[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United #
#States.1252
#[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
#[5] LC_TIME=English_United States.1252
#attached base packages:
#[1] stats graphics grDevices utils datasets methods base
#other attached packages:
#[1] devEMF_3.6
#loaded via a namespace (and not attached):
#[1] tools_3.3.2

Some of the defaults in that function are not ideal if you are trying to view outside of LibreOffice.
try this:
library(devEMF)
emf(file = "trial.emf", emfPlus = FALSE)
plot(1:10, seq(10, 100, 10), type = "l", xlab = "Time", ylab = "Distance")
dev.off()
Make sure that emfPlus = FALSE. If you view the plot generated by emfPlus = TRUE in LibreOffice you will see it looks fine. Use emfPlus = FALSE when working with other viewers.

Most likely the program being used to view the resulting emf graphic does not support EMF+ records.
As alluded in JMT2080AD's answer, the devEMF library can produce either "EMF" or "EMF+" files. The newer EMF+ format (https://msdn.microsoft.com/en-us/library/cc230724.aspx) has been around since 2007 and is supported by more recent closed-source programs (i.e., Office 2010) but support is missing from old programs (e.g., older versions of Adobe Illustrator) and spotty in many open-source programs (e.g., LibreOffice, Inkscape).
For better or for worse, EMF+ records are embedded within EMF comment records, which means older programs will silently ignore them.
I find that the devEMF defaults produce acceptable files for Microsoft Office 2010 and LibreOffice >5.1.6. While LibreOffice support for EMF+ is incomplete, the unsupported features are turned off by default in the call to emf(). That said, JMT2080AD's suggestion of setting emfPlus = FALSE in the call to emf() is likely to make the files viewable by more programs (at the cost of losing features such as transparency and anti-aliasing).
(Disclosure: I am the author of the devEMF package)

Related

problem with svg device, expression(), and unicode characters

I am having difficulty using the svg device with math expressions and unicode (in this case, left- and right-quotes). This only occurs on my Windows 10 computer; my osx computer seems unaffected. Consider the following R code:
output = tempfile(fileext = ".svg")
svg(file = output)
plot(1, axes=FALSE, ty='n')
## Line A:
mtext(side = 2, text = expression(paste("A")))
## Line B:
mtext(side = 3, text = expression(paste("“B")))
## Line C:
mtext(side = 4, text = expression(paste("C")))
axis(1, at = par()$usr[1:2], lab = c("More", "Less"), tick = FALSE)
dev.off()
## Uncomment and run to open the SVG file to look at it
# browseURL(output)
(Note the left-quote in Line B). Upon running Line C, I get
Error in mtext(side = 4, text = expression(paste("C"))) :
metric information not available for this device
If I change the device to png I get the output I expect.
If I comment out lines B and C, I get the output I expect (eg, the output from lines A and the axis)
If I comment out only line C, I do not get the output I expect. Neither line B works, nor the axis. There appears to be something wrong with line B that causes everything later in the chunk to fail too.
If I remove the expression() from line B, everything works as expected (including the unicode left-quote)
If I change the font using showtext (see the issue for details: https://github.com/yihui/knitr/issues/1831) I have no problem.
This appears, then, to be an interaction between svg, expression, the default font, and unicode. But only on Windows 10. My OSX computer (see details below) does not have the issue.
sessionInfo()
R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] reprex_0.3.0
loaded via a namespace (and not attached):
[1] Rcpp_1.0.4.6 ps_1.3.2 digest_0.6.25 R6_2.4.1 evaluate_0.14 rlang_0.4.5 fs_1.4.1
[8] callr_3.4.3 whisker_0.4 rmarkdown_2.1 Cairo_1.5-12 tools_3.6.2 xfun_0.13 compiler_3.6.2
[15] processx_3.4.2 clipr_0.7.0 htmltools_0.4.0 knitr_1.28.3
OSX session info (no problem on this computer)
> xfun::session_info('knitr')
R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.4, RStudio 1.2.5031
Locale: en_GB.UTF-8 / en_GB.UTF-8 / en_GB.UTF-8 / C / en_GB.UTF-8 / en_GB.UTF-8
Package version:
evaluate_0.14 glue_1.4.0 graphics_3.6.1 grDevices_3.6.1
highr_0.8 knitr_1.28.3 magrittr_1.5 markdown_1.1
methods_3.6.1 mime_0.9 stats_3.6.1 stringi_1.4.6
stringr_1.4.0 tools_3.6.1 utils_3.6.1 xfun_0.12
yaml_2.2.1
Any idea what is causing this?
I get the same problem on my 32-bit Windows work PC. It's a tricky error to track down, but I eventually found it is being thrown here in the GMMathText function of graphics.c. As you describe, it only seems to be a problem with expressions containing certain characters on some graphics devices. In particular, anything using Cairo on Windows seems to stub its toe at the same point.
After attempting several hacks to get around this, I found that the best solution is to simply use bquote instead of expression. This allows you to keep all of the plotmath functionality you get with expression without generating the error:
svg(output)
plot(1, axes=FALSE, ty='n')
mtext(side = 2, text = bquote("A"))
mtext(side = 3, text = bquote("“B"))
mtext(side = 4, text = bquote("C"))
axis(1, at = par()$usr[1:2], lab = c("More", "Less"), tick = FALSE)
dev.off()
Which gives the following SVG:
There is a nice overview of how to use bquote to generate your labels, including all the maths expressions you need here
I'm taking something of a guess here because I know nothing about R. However the local for your windows box is cp1252 which does not contain Unicode quotes but uses Microsoft's smart quotes.
You say it works in OS-X which looking at your session info is set up to use UTF-8.
I'm assuming that your program file is saved as UTF-8.

Make R Studio plots only show up in new window

When using R Studio, I usually just work with an .R file stacked on top of the Console. I keep the other panes (Environment, History, Files, etc) hidden.
But whenever I plot a graph, the other panes automatically pop out of the side bar to show me the Plot pane. Because I work on a laptop, this makes everything too small to see. By clicking the Zoom button on the Plots pane, I can get the plot also show up in a new window, but does not prevent the Plots pane from showing up.
Is there a way to "disable" the Plots pane in R Studio, and force plots show up in a new window?
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils
[5] datasets methods base
other attached packages:
[1] ggplot2_2.2.1 jsonlite_1.4
[3] data.table_1.10.4
loaded via a namespace (and not attached):
[1] labeling_0.3 colorspace_1.2-6
[3] scales_0.4.1 lazyeval_0.2.0
[5] plyr_1.8.4 tools_3.2.3
[7] gtable_0.1.2 tibble_1.3.0
[9] curl_2.5 Rcpp_0.12.10
[11] grid_3.2.3 munsell_0.4.2
>
The dev.new() function will open a new plot window, which then becomes the target for all plots.
If you wish to open another window you can run the command a second time to open a second window.
dev.off() will shut down the window (in the order they were opened by default).
You can see how to control multiple graphics devices in the documentation here.
In RStudio, the default graphics device is normally "RStudioGD". You can change that to something else: the normal choices are "windows" on Windows, "quartz" on MacOS, "X11" on Linux. So for example, use
options(device = "quartz")
in your RStudio session on a Mac and you'll get the regular MacOS graphics window.
Try using the windows command before your plot call.
windows();(mpg ~ wt, mtcars)
The plot should pop-up in its own window whilst the pane stays minimized.
Commenting the following lines in C:\Program Files\RStudio\R\Tools.R seems to work (it may be necessary to edit the file as administrator):
# set our graphics device as the default and cause it to be created/set
.rs.addFunction( "initGraphicsDevice", function()
{
# options(device="RStudioGD")
# grDevices::deviceIsInteractive("RStudioGD")
grDevices::deviceIsInteractive()
})
If you want all plots in the current script to appear on a separate window, this should do the job:
dev.new(noRStudioGD = TRUE)
*Tested on RStudio version 1.4.1106 for Windows with R version 4.0.5 (2021-03-31)
For a 'permanent' solution, the answer by Rubén Fernández-Casal should work well.
You can force RStudio to show plots in the Source window if you use R Markdown. In a Rmd file, plots are shown together with code; it's called an R Markdown notebook. You can set the size of the plots too, in what is called an R code chunk:
```{r fig.height = 2, fig.width = 3}
plot(mpg ~ wt, mtcars)
```
When you run the chunk, the plot is shown below it.
If you want to set the plot size for the whole notebook, set the package option using opts_knit and opts_chunk, for example:
```{r setup}
library(knitr)
opts_knit$set(global.par = TRUE)
opts_chunk$set(fig.width = 4.5, fig.height = 3.5)
```
For more information, see here and here.

Displaying UTF-8 encoded characters in R

I am using the RODBC package to read data from SQL server. R is reading the Chinese characters as "?????"
I have passed the parameter DBMSencoding = "UTF-8" to the odbcConnect function.
Following is the sample code I am using:
Connection <- odbcConnect("abc", uid = "123", pwd = "123",
DBMSencoding = "UTF-8", readOnlyOptimize=T)
Var1 <- sqlQuery(Connection, query, errors = TRUE, stringsAsFactors=F)
May be I didn't pass the arguments the way I am supposed to?
sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] RODBC_1.3-12
loaded via a namespace (and not attached):
[1] tools_3.2.3
odbcGetInfo(mainConnection)
DBMS_Name DBMS_Ver Driver_ODBC_Ver Data_Source_Name Driver_Name
"Microsoft SQL Server" "10.50.4000" "03.52" "SQLSRV32.DLL"
Driver_Ver ODBC_Ver Server_Name
"06.01.7601" "03.80.0000"
Check the database's character encoding:
select userenv('language') from dual;
SIMPLIFIED CHINESE_CHINA.AL32UTF8
Change your Environment Variable NLS_LANG before connecting to the database:
Sys.setenv(NLS_LANG="SIMPLIFIED CHINESE_CHINA.AL32UTF8")
Connection <- odbcConnect("abc", uid = "123", pwd = "123", DBMSencoding = "UTF-8", readOnlyOptimize=T)
R on Windows has a lot of problems displaying characters outside of ASCII, even though it is often faithfully representing them internally. There is a lot of information in this answer about why this is the case, and some simple diagnostics in this answer. First try plotting, like:
# first, make sure plotting Chinese works in general
# (i.e., you have an appropriate font)
hanzi <- "漢字"
plot(1, 1, type="n")
text(1, 1, hanzi)
If that works, replace the hanzi <- "漢字" line with your sql query line to get some Chinese text from your database into a string variable, and try plotting that. If it shows up on the plot, then the characters are being read fine and represented internally fine, and the problem is just displaying them in the console. If plotting worked for the "漢字" string variable but doesn't work for your SQL-extracted string, then at least you know that the problem is actually with the SQL part and not just with display in the console.
I got the same problem and successfully solved it. It was quite simple. Go to Control Panel --> Region and Language --> Administrative --> Change system locale --> Chinese.

Error: "could not find function "lengths"

While running:
reg_model = glmer(modeling1 ~ pTOT_VIOPT_CT + (1|STUDY_CODE_ALIAS),
data=data_CACZ, family=binomial)
I am getting the error:
Error in .fixupDimnames(.Object#Dimnames) :
could not find function "lengths"
Not sure what could be the possible reason.
FYI: I am putting below the sessionInfo():
R version 3.0.2 (2013-09-25)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] Rcpp_0.11.5 lme4_1.1-10 Matrix_1.2-3 car_2.0-21 MASS_7.3-29
loaded via a namespace (and not attached):
[1] grid_3.0.2 lattice_0.20-29 minqa_1.2.4 nlme_3.1-118 nloptr_1.0.4 nnet_7.3-7 splines_3.0.2 tools_3.0.2
(From the maintainer of 'Matrix'): This is indeed really strange,
but differently than #nicola suggests.
It is okay to update Recommended packages such as Matrix without updating R. That's indeed one feature of these.
Matrix 1.2-3 is indeed the current version of Matrix on CRAN, which is good.
However, since Matrix 1.2-2, there is the following code in Matrix/R/zzz.R :
if(getRversion() >= "3.2.0") {
......
} else {
......
lengths <- function (x, use.names = TRUE) vapply(x, length, 1L, USE.NAMES = use.names)
}
But that code only works correctly for you, when the Matrix package is built from the source with a correct version of R, i.e. in your case with a version of R before 3.2.0.
This (correctly built) happens for all platforms but Windows (the broken by choice one).
If you really don't want (or can't easily) upgrade your version of R,
you have two other options:
downgrade your version of Matrix to the one that comes with your version of R. As you probably have installed the new Matrix replacing the old one, you need to get that and replace the newer version of Matrix. HOWEVER, I guess you would also have to downgrade lme4, and in the end you suffer too much.
Safer and in principle correct: Install the 'Rtools' collection for Windows (you need the one that matches your version of R !)
including C compiler etc, until the following works correctly
install.packages("Matrix", type = "source")
The work to do this may well be worth it. You will be able to install other R packages from their source, which is very useful anyway
(I would not want to live without this possibility if I had to work with Windows).

Unicode in rgl plot3d

I'm all new to R, and the rgl packageand having searched all over all day for a solution...
I'm trying to use rgl's text3d function with unicode text. I have no problem plotting the same chars in 2D (using text()), but in 3D, instead of rendering the symbols it just writes out the UTF-8 char codes (unless they're ascii chars).
I'm reading in data from file where the column "vowel" contains the symbols to be plotted (e.g. "e i ə ɪ ɒ" etc.), and cols "F1", "F2" and "F3" contain the values to be plotted. The file is read in with read.delim with encoding="UTF-8"; and inspecting the data in the RGui shows the UTF-8 char codes for any non-ascii symbols.
Sample data (comma-delimited)
vowel,F1,F2,F3
i,424.1352452,1985.143387,2549.272611
e,515.0401373,1693.077496,2534.527142
ə,408.8233704,1589.12993,2567.448424
ɒ,490.6565129,1070.564989,2590.467597
ɪ,405.5223379,1665.733731,2261.069994
u,360.0803517,1798.355786,2354.845875
ɜ,541.6360766,1323.593646,2435.121753
ɑ,718.8871543,1139.013741,2820.694337
ɑ,629.1691413,1064.047107,2910.997552
ɪ,375.0097039,2091.996102,2648.991664
This is the code I've been testing with:
d <- read.delim("my.filename", header=TRUE, sep=",", encoding="UTF-8")
Plotting in 3D (plots things like "<\U+0252>" etc. (escaped here!) for all non-ASCII chars):
library(rgl)
cols <- c("F1", "F2", "F3");
plot3d(d[,cols], xlab="F1", ylab="F2", zlab="F3", type="n");
text3d(d[,cols], col=1, text=d$vowel);
Plotting in 2D (works):
cols <- c("F1", "F2");
plot(d[,cols], xlab="F1", ylab="F2", type="n");
text(d[,cols], col=1, labels=d$vowel);
Does it have something to do with OpenGL? I've installed freetype, hoping that might solve the issue, but I haven't managed to point R to it - so it issues warnings "par3d(useFreeType = TRUE) : FreeType not supported in this build" and "In par3d(useFreeType = TRUE) : font family "sans" not found, using "bitmap""...
Having spent several hours battling R for freetype, I was hoping someone here can tell me whether freetype will even solve the issue??! If yes, a hint as to what "Set the environment variable LIB_FREETYPE to give the full path to the install directory" (from rgl README) is trying to tell me to do would be hugely appreciated!
Thank you.
My sessionInfo:
R version 3.0.2 (2013-09-25)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
LC_COLLATE=English_United Kingdom.1252
LC_CTYPE=English_United Kingdom.1252
LC_MONETARY=English_United Kingdom.1252
LC_NUMERIC=C
LC_TIME=English_United Kingdom.1252
attached base packages:
stats graphics grDevices utils datasets methods base
other attached packages:
rgl_0.93.975
You need to have FreeType installed.
Make sure you have FreeType and FreeType Open GL libraries installed, then reinstall rgl in R and then everything works.
See here also : http://www.smnd.sk/kotanyi/index.php?page=rgl

Resources