Save plot without showing it at all - r

Is it possible to save a plot without displaying it at all ?
I made a little ggplot hack to be able to copy graphs to powerpoint easily, it copies the plot to the clipboard, but one can see the device window open and close fast, it's a bit awkward, can I avoid this ?
I'm using windows and rstudio.
reproducible code:
library(ggplot)
`-.gg` <- function(e1,e2){
assertthat::assert_that(is.numeric(e2),
length(e2)<= 2)
if(identical(e2,0)) return(invisible(NULL))
W <- 8
H <- 4.5
dev.new(width=W * head(e2,1), height=H * tail(e2,1),noRStudioGD =TRUE)
print(e1)
savePlot("clipboard", type="wmf")
dev.off()
e1
}
ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0
Edit:
My code, and chosen solution, have issues dealing with semi-transparency.It's ok most of the time, but exceptions will be annoying.
Maybe a path to a general solution would be to save it with tempfile then read it into the clipboard, either through an appropriate R function, or with command line using system (maybe something that would open the file invisibly and copy).

This works on Windows: use the win.metafile() device. If you give no filename, it saves to the clipboard. So your function should be
library(ggplot2)
`-.gg` <- function(e1,e2){
assertthat::assert_that(is.numeric(e2),
length(e2)<= 2)
if(identical(e2,0)) return(invisible(NULL))
W <- 8
H <- 4.5
win.metafile(width=W * head(e2,1), height=H * tail(e2,1))
print(e1)
dev.off()
e1
}
ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0

On windows and R 3.4.2, using Sys.sleep was able to view the plot instead of blink and miss
`-.gg` <- function(e1,e2){
assertthat::assert_that(is.numeric(e2),
length(e2)<= 2)
if(identical(e2,0)) return(invisible(NULL))
W <- 8
H <- 4.5
dev.new(width=W * head(e2,1), height=H * tail(e2,1),noRStudioGD =TRUE)
print(e1)
savePlot("clipboard", type="wmf")
Sys.sleep(3) ##
dev.off()
e1
}
ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0

Related

Combine two outputs in a single box in RStudio

I am extremely new to R.
This simple code prints two outputs:
ec_lineal = function(a,b){
print(sprintf('%i x + %i = 0',a,b))
paste(sprintf('x ='), -b / a)
}
ec_lineal(5,3)
[1] "5 x + 3 = 0"
[1] "x = -0.6"
When I knit the code to HTML, I get separate boxes for each of the outputs:
Is there any way to combine both outputs in a single white box?
Maybe editing the code chunk header ```{r} ?
I am using R 3.6.3 and the latest version of RStudio in Windows 10.
Thank you.
You may use cat.
ec_lineal = function(a,b) {
cat(sprintf('%i x + %i = 0',a,b),
paste(sprintf('x ='), -b / a),
sep="\n")
}
ec_lineal(5,3)
# 5 x + 3 = 0
# x = -0.6

How to print plus-minus and beta signs in bquote, and correctly export to pdf

¿How do you print the ± sign in a bquote() expression in R?
I have tried the following:
pm
%pm%
±
These have not worked.
UPDATE #1 Here is some sample code
plot(NULL,xlim=c(0,10),ylim=c(0,10),xlab=NA,ylab=NA,xaxs="i",yaxs="i")
c <- "name"
p <- .004
n <- 969
b <- 1.23
s <- 0.45
tmp.txt <- paste(c(c," (n=",n,")\nslope = ",b,"±",s,"\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,9.5,labels=tmp.txt,adj=c(1,1),cex=.75)
What I am trying to do is to make the 2nd line have beta (the symbol) instead of slope, and the ± symbol to appear. If I use expression, I can get the beta, but not the ±; if I just paste in ß (or something similar), it won't run.
UPDATE #2: It appears I HAVE to use bquote()...else the beta character won't print when piped out via pdf().
An answer to this question suggests using paste with bquote. You could then use the Unicode character of ±:
x <- 232323
plot(1:10, main = bquote(paste(ARL[1], " curve for ", S^2, "; x=\U00B1",.(x))))
Note that this example (minus the inclusion of \U00B1) came from fabian's answer to the previously linked question.
I appreciate the advice given, but it didn't fully accomplish my goal. Here is the workaround I came up with (and I personally think it is just short of asinine...but I'm at a loss).
c <- "name"
p <- .004
n <- 969
b <- 1.23
s <- 0.45
## draw empty plot
plot(NULL,xlim=c(0,10),ylim=c(0,10),xlab=NA,ylab=NA,xaxs="i",yaxs="i")
## place the "poor man's substitute"
tmp.txt <- paste(c(c," (n=",n,")\nslope = ",b,"±",s,"\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,9.5,labels=tmp.txt,adj=c(1,1),cex=.75)
## place the next best option
tmp.txt <- paste(c(c," (n=",n,")\n\U03B2 = ",b,"±",s,"\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,7.5,labels=tmp.txt,adj=c(1,1),cex=.75)
## place the two boxes to superimpose the bquote() version
tmp.txt2 <- paste(c(c," (n=",n,")\n\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,5.5,labels=tmp.txt2,adj=c(1,0.5),cex=.75)
text(9.5,5.5,labels=bquote(beta == .(b)%+-%.(s)),adj=c(1,0.5,cex=.75))
## same as above, but piped to a *.pdf
pdf("tmp_output.pdf")
plot(NULL,xlim=c(0,10),ylim=c(0,10),xlab=NA,ylab=NA,xaxs="i",yaxs="i")
tmp.txt <- paste(c(c," (n=",n,")\nslope = ",b,"±",s,"\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,9.5,labels=tmp.txt,adj=c(1,1),cex=.75)
tmp.txt <- paste(c(c," (n=",n,")\n\U03B2 = ",b,"±",s,"\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,7.5,labels=tmp.txt,adj=c(1,1),cex=.75)
tmp.txt2 <- paste(c(c," (n=",n,")\n\n",ifelse(p==0,"p<.001",paste0("p=",p))),collapse="")
text(9.5,5.5,labels=tmp.txt2,adj=c(1,0.5),cex=.75)
text(9.5,5.5,labels=bquote(beta == .(b)%+-%.(s)),adj=c(1,0.5,cex=.75))
dev.off()
If you run this, it appears to work both inside of R and in the resulting *.pdf file.
As always, a more elegant (and sensible) solution would be much appreciated.

Calculate Taylor series using rSymPy

I have been trying out the R interface rSymPy to the CAS SymPy and it works quite well. However, I cannot find the correct syntax for using some of the more complex features, such as finding a Taylor series.
For example, I have tried the following:
library(rSymPy)
sympy("var('p')")
#
##### Cannot make this work ???
#
sympy("from sympy.mpmath import *")
xt <- sympy("p=taylor(exp, 0, 10)")
But it throws the error:
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
SyntaxError: ("no viable alternative at input '='", ('<string>', 1, 8, '__Rsympy= from sympy.mpmath import *\n'))
Any help appreciated.
There does not appear to be an explicit Taylor series available, but the series function is available. The following code works:
library(rSymPy)
sympy("var('p')")
sympy("var('x')") # or sympy("x = Symbol('x', real=True)")
#
xt <- sympy("p=series(exp(x), x, 0, 10)") # expand about 0 to 10th order
which gives the answer:
[1] "1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + O(x**10)"
We can check this answer by modifying the code to:
library(rSymPy)
sympy("var('p')")
sympy("var('x')") # or sympy("x = Symbol('x', real=True)")
#
xt <- sympy("p=series(exp(x), x, 0, 10)") # expand about 0 to 10th order
# Remove order information
xt0 <- sympy("p.removeO()")
# Test results
x <- 1/3
T1 <- eval(parse(text=xt0)) # Evaluate the result, xt0
T2 <- exp(x) # The correct value
print(T1-T2) # Print the error
Finally, the error from the series expansion is:
[1] -4.811929e-12
I hope this is helpful to anyone else wishing to use the R package rSymPy

Importing data into R (rdata) from Github

I want to put some R code plus the associated data file (RData) on Github.
So far, everything works okay. But when people clone the repository, I want them to be able to run the code immediately. At the moment, this isn't possible because they will have to change their work directory (setwd) to directory that the RData file was cloned (i.e. downloaded) to.
Therefore, I thought it might be easier, if I changed the R code such that it linked to the RData file on github. But I cannot get this to work using the following snippet. I think perhaps there is some issue text / binary issue.
x <- RCurl::getURL("https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData")
y <- load(x)
Any help would be appreciated.
Thanks
This works for me:
githubURL <- "https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData"
load(url(githubURL))
head(df)
# X Y Z
# 1 16602794 -4183983 94.92019
# 2 16602814 -4183983 91.15794
# 3 16602834 -4183983 87.44995
# 4 16602854 -4183983 83.79617
# 5 16602874 -4183983 80.19643
# 6 16602894 -4183983 76.65052
EDIT Response to OP comment.
From the documentation:
Note that the https:// URL scheme is not supported except on Windows.
So you could try this:
download.file(githubURL,"myfile")
load("myfile")
which works for me as well, but this will clutter your working directory. If that doesn't work, try setting method="curl" in the call to download.file(...).
I've had trouble with this before as well, and the solution I've found to be the most reliable is to use a tiny modification of source_url from the fantastic [devtools][1] package. This works for me (on a Mac).
load_url <- function (url, ..., sha1 = NULL) {
# based very closely on code for devtools::source_url
stopifnot(is.character(url), length(url) == 1)
temp_file <- tempfile()
on.exit(unlink(temp_file))
request <- httr::GET(url)
httr::stop_for_status(request)
writeBin(httr::content(request, type = "raw"), temp_file)
file_sha1 <- digest::digest(file = temp_file, algo = "sha1")
if (is.null(sha1)) {
message("SHA-1 hash of file is ", file_sha1)
}
else {
if (nchar(sha1) < 6) {
stop("Supplied SHA-1 hash is too short (must be at least 6 characters)")
}
file_sha1 <- substr(file_sha1, 1, nchar(sha1))
if (!identical(file_sha1, sha1)) {
stop("SHA-1 hash of downloaded file (", file_sha1,
")\n does not match expected value (", sha1,
")", call. = FALSE)
}
}
load(temp_file, envir = .GlobalEnv)
}
I use a very similar modification to get text files from github using read.table, etc. Note that you need to use the "raw" version of the github URL (which you included in your question).
[1] https://github.com/hadley/devtoolspackage
load takes a filename.
x <- RCurl::getURL("https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData")
writeLines(x, tmp <- tempfile())
y <- load(tmp)

ggplot2 not saving geom_raster() plots correctly

I plotting a 52 x 52 matrix with geom_raster through ggplot.
Code is here:
m <- NULL
for(i in 1:nrow(df)){
for(z in 1:nrow(df)){
if(df[i,][4] > df[z,][4]){m<-c(m,((df[i,][[4]]/df[z,][[4]])*100)-100)}
if(df[i,][4] < df[z,][4]){m<-c(m,((df[z,][[4]]/df[i,][[4]])*100)-100)}
if(df[i,][4] == df[z,][4]){m<-c(m,0.0)}}}
m <- matrix(m,nrow=nrow(df))
colnames(m) <- df$PDB
rownames(m) <- df$PDB
p1 <- ggplot(melt(m),aes(Var1,Var2,fill=value)) + geom_raster() + labs(x="PDB",y="PDB")
p1 <- p1 + theme(axis.text.x = element_text(angle=90,hjust=1))
print(p1)
ggsave(file="ccs_diff_ehss.pdf")
The issue I have is when I save the file I get the following outputs:
Through file > save as >:
Through ggsave:
Output from print(p1):
As you can see the out from print(p1) as a lot sharper than ggsave and manual saving. How can I save the images as outputted from print(p1)?
Here is a subsbset of my matrix:
1a29 1cll 1clm 1cm1 1exr 1g4y 1iq5 1lin 1mxe1 1mxe2
1a29 0.000000 18.8967136 19.0727700 3.814554 20.539906 19.3075117 9.330986 1.584507 5.6924883 5.8098592
1cll 18.896714 0.0000000 0.1480750 14.527982 1.382034 0.3455084 8.749329 17.042172 12.4930594 12.3682751
1clm 19.072770 0.1480750 0.0000000 14.697569 1.232134 0.1971414 8.910360 17.215482 12.6596335 12.5346644
1cm1 3.814554 14.5279819 14.6975692 0.000000 16.110797 14.9236857 5.313737 2.195263 1.8089316 1.9219898
1exr 20.539906 1.3820336 1.2321341 16.110797 0.000000 1.0329562 10.252281 18.659734 14.0477512 13.9212424
1g4y 19.307512 0.3455084 0.1971414 14.923686 1.032956 0.0000000 9.125067 17.446563 12.8817324 12.7565169
1iq5 9.330986 8.7493290 8.9103596 5.313737 10.252281 9.1250671 0.000000 7.625650 3.4425319 3.3277870
1lin 1.584507 17.0421722 17.2154824 2.195263 18.659734 17.4465627 7.625650 0.000000 4.0439053 4.1594454
1mxe1 5.692488 12.4930594 12.6596335 1.808932 14.047751 12.8817324 3.442532 4.043905 0.0000000 0.1110494
1mxe2 5.809859 12.3682751 12.5346644 1.921990 13.921242 12.7565169 3.327787 4.159445 0.1110494 0.0000000
I realize this is an older thread but it looks like it gets about 7 views a month. Perhaps this will help those visitors:
There is a chance that the image viewer application itself is applying a smoothing algorithm. I came across your post while trying to resolve the same issue and eventually discovered that I needed to turn off smoothing in the PDF viewer preferences. Now the output file looks identical to the plot in R.
This is the thread that tipped me off (includes some extra directions about where to locate the settings). https://groups.google.com/forum/#!topic/ggplot2/8VLuo1cw6SE
Take a look at the ggsave documentation -- perhaps you can increase your resolution by manually specifying the dimensions or the dpi.

Resources