ggmap missing background map (except when using pdf device) - r

I am using the ggmap library in R to produce a map of the Atlanta area. When running the code, I'm able to get points plotted on the map as well as other layers, but am not able to get the map itself to print in any graphics device other than PDF. I suspect a configuration issue as I'm able to use this code on a different computer without issue, but two other machines simply display blank plots.
Here is a scaled down version of the code. I am assuming that my blank plots won't be reproducible, but I'm hoping to get some guidance on where the configuration problem might be.
library('ggplot2')
library('ggmap')
library('mapproj')
# ggmapTemp.png gets saved to the working directory correctly
atlanta <- get_map(location=c(lon=-84.26039,
lat=33.8751),
zoom=9,maptype='roadmap')
atlantaMap <- ggmap(atlanta, extent = 'device', legend = 'topleft')
# this produces a blank plot from both RStudio as well as R
atlantaMap
# this produces the actual map correctly
pdf("plot.pdf")
atlantaMap
dev.off()
# this produces a png file with only a white background
png("plot.png")
atlantaMap
dev.off()
Session Info:
R version 2.15.3 (2013-03-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
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] mapproj_1.2-1 ggmap_2.3 ggplot2_0.9.3.1 maps_2.3-6 maptools_0.8-27
[6] sp_1.0-14 car_2.0-19 reshape2_1.2.2 plyr_1.8 Revobase_6.2.0
[11] RevoMods_6.2.0 RevoScaleR_6.2.0 lattice_0.20-13 rpart_4.1-0
loaded via a namespace (and not attached):
[1] codetools_0.2-8 colorspace_1.2-4 dichromat_2.0-0 digest_0.6.3 foreach_1.4.0
[6] foreign_0.8-52 grid_2.15.3 gtable_0.1.2 iterators_1.0.6 labeling_0.2
[11] MASS_7.3-23 munsell_0.4.2 nnet_7.3-5 png_0.1-6 proto_0.3-10
[16] RColorBrewer_1.0-5 RgoogleMaps_1.2.0.5 rjson_0.2.13 RJSONIO_1.0-3 scales_0.2.3
[21] stringr_0.6.2 tools_2.15.3
And capabilities:
jpeg png tiff tcltk X11 aqua http/ftp sockets libxml fifo cledit
TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE
iconv NLS profmem cairo
TRUE TRUE TRUE TRUE

The problem has to do with the server limiting the bit depth that gets passed through the connection. Oracle documents the problem and solution on their site:
In a Remote Desktop session, all environment variables, including display variables determining Color Depth, are determined by the RCP-Tcp connection settings. For example, users can reduce the Color Depth when connecting over a slow connection. The different settings are 15 bits, 16 bits, 24 bits, or 32 bits per pixel. To raise the Remote Desktop color depth:
On the Windows server, launch Remote Desktop Session Host Configuration from the Accessories menu.
Under Connections, right click on RDP-Tcp and select Properties.
On the Client Settings tab either uncheck LimitMaximum Color Depth or set it to 32 bits per pixel.
Upon unchecking the "Limit Maximum Color Depth" check box and reconnecting to the server, the raster map backgrounds now show up as expected. Note that they also provide option 2 which is to output to an alternate device.

It seems jrshrenk haven't updated R and the packages in a while. Although in theory your versions of R, ggmap, png and ggplot2 seems sufficient:
Package: ggmap
Version: 2.4
Depends: R (>= 2.14.0), ggplot2 (>= 0.9.2)
Imports: proto, scales, RgoogleMaps, png, plyr, reshape2, grid, rjson,
mapproj, jpeg, geosphere, digest
Suggests: MASS, stringr
License: GPL-2
NeedsCompilation: no
Package: png
Version: 0.1-7
Depends: R (>= 2.9.0)
License: GPL-2 | GPL-3
NeedsCompilation: yes
I would just try to update R and the packages to see if it solves the issue:
#Save your current packages but not the base ones:
savepackages <- rownames(installed.packages(priority='NA'))
write(savepackages, file="listpackages.txt")
#Check for Updates of R
library(installr)
check.for.updates.R(notify_user = TRUE, use_GUI = TRUE,
page_with_download_url = "http://cran.rstudio.com/bin/windows/base/",
pat = "R-[0-9.]+-win")
#Download and Install New Version
install.R(page_with_download_url = "http://cran.rstudio.com/bin/windows/base/",
pat = "R-[0-9.]+-win.exe", to_checkMD5sums = TRUE,
keep_install_file = TRUE, download_dir = tempdir(), silent = FALSE)
#Then reinstall packages
pkg.ls <- read.table("listpackages.txt")
install.packages(pkg.ls)

Related

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.

ggtern disables some themes from ggplot2

Trying to switch the theme to theme_bw() is not working, theme_grey() seems to be prioritized. Any ideas why?
ggplot(data=mpg,aes(y=year,x=cyl)) + geom_point() + theme_bw()
EDIT:
As suggested in the comments, this works when run in a clean R session. But when I implement the code in a session with ggtern loaded, the problem crops up.
library(ggplot2)
#Warning message:
#package ‘ggplot2’ was built under R version 3.2.5
ggplot(data=mpg,aes(y=year,x=cyl)) + geom_point() + theme_bw()
# sessionInfo()
# R version 3.2.2 (2015-08-14)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 8 x64 (build 9200)
#
# 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] ggplot2_2.1.0
#
# loaded via a namespace (and not attached):
# [1] labeling_0.3 colorspace_1.2-6 scales_0.4.0 plyr_1.8.3 tools_3.2.2 gtable_0.1.2
# [7] Rcpp_0.12.2 grid_3.2.2 munsell_0.4.2
library(ggtern)
#Loading required package: ggplot2
#Attaching package: ‘ggtern’
#The following objects are masked from ‘package:ggplot2’:
#aes, calc_element, ggplot, ggplot_build, ggplot_gtable, ggplotGrob, ggsave, is.ggplot, layer_data,
#layer_grob, layer_scales, theme, theme_bw, theme_classic, theme_dark, theme_get, theme_gray,
#theme_light, theme_linedraw, theme_minimal, theme_set, theme_void
#Warning messages:
#1: package ‘ggtern’ was built under R version 3.2.5
#2: package ‘ggplot2’ was built under R version 3.2.5
ggplot(data=mpg,aes(y=year,x=cyl)) + geom_point() + theme_bw()
# sessionInfo()
# R version 3.2.2 (2015-08-14)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 8 x64 (build 9200)
#
# 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] ggtern_2.1.1 ggplot2_2.1.0
#
# loaded via a namespace (and not attached):
# [1] Rcpp_0.12.2 lattice_0.20-33 MASS_7.3-45 grid_3.2.2 plyr_1.8.3
# [6] bayesm_3.0-2 gtable_0.1.2 magrittr_1.5 scales_0.4.0 stringi_1.0-1
# [11] compositions_1.40-1 robustbase_0.92-5 latex2exp_0.4.0 boot_1.3-17 labeling_0.3
# [16] proto_0.3-10 tools_3.2.2 stringr_1.0.0 energy_1.6.2 DEoptimR_1.0-4
# [21] munsell_0.4.2 colorspace_1.2-6 tensorA_0.36 gridExtra_2.0.0
Looks like ggtern masks a lot of the themes from ggplot2.
ggtern masks EVERY default theme from ggplot2, and this is because when writing this software, some ~60 new theme elements have been created, which exist in order to make ggtern render correctly. For a comprehensive list of the new theme elements, run the following command:
library(ggtern)
?theme_elements
Having said the above, I was aware of some clashes, as you have identified, due to ggtern also modifying some of the base theme elements, and since about version 2.1.2 - 2.1.3, I have completely re-worked the themes so that ggtern no longer modifies any of the base elements -- hopefully this annoying behaviour has now gone away for good!
I am in the process of producing a publication on the package, and have been refining many many many long-tern annoyances, so please download and install the most recent version (2.1.4) from my (Bitbucket Repository). Embarrassingly, even the last 2.1.3 version on CRAN, I picked up on a pretty significant bug when running two plots in a grid.arrange type situation. This is an issue with the clipping mask, and something which has been resolved in 2.1.4 yet sent to CRAN, something I plan to do imminently.
Anyway, to answer your question, please upgrade your version, you are running version 2.1.0, which was a version released not long after a HUGE revision in ggplot2 -- in fact, not long earlier, prior versions were so heavily broken, requiring almost the entire re-writing of ggtern, so having perfect themes was the least of my priorities. In recent versions, since I have had time to refine and identify issues, this behaviour should have been resolved -- demonstrated by the following two (2) commands run (in this order, from a clean session), which, with the exception of the obvious difference in the titles, should yield identical results:
library(ggplot2)
ggplot(data=mpg,aes(y=year,x=cyl)) +
geom_point() + theme_bw() +
labs(title='From ggplot2')
library(ggtern)
ggplot(data=mpg,aes(y=year,x=cyl)) +
geom_point() + theme_bw() +
labs(title='From ggtern')
If I can just say, this may seem a little off-topic, but this whole problem actually originally stemmed, by a couple of degrees of separation, from one thing. ggplot2 was designed without clipping masks, it uses the grid viewport as essentially a pseudo clipping mask, because all of its plots (with the exception of the polar transformation), are rendered on a rectangular region. Data mappings that lie outside of the rectangular region are subsequently discarded by the viewport. ggtern on the other hand needs one, because it needs to render within a triangular shaped polygon region housed within a rectangular viewport -- and as everyone knows, 'triangles don't fit in square holes' or however the saying goes! When the axis limits are reduced, data mappings can, and often do, lie outside of the triangular region, and these need to be either deleted or masked (or shown if the user so wishes). Deleting is not an option, since it would then affect certain plots like polygon, path, density or contour plots (I think probably point geometries are the only ones which are not potentially affected), which leaves only one option -- implementation of clipping mask. In some of the earlier versions, a clipping mask wasn't implemented (in favour of subsetting the data) thus requiring modifications of base theme elements. If anything, perhaps an initial 'poor design', has flowed on many generations later to a frustrating behaviour.
ggtern masks theme_bw(), meaning that ggtern has its own version of theme_bw() that overrides the ggplot2 version. Oddly, ggtern's version of theme_bw() looks like theme_grey(), so maybe that's a bug.
If you want to keep ggtern loaded, another option is to enforce the ggplot2 version of theme_bw():
ggplot(data=mpg,aes(y=year,x=cyl)) + geom_point() + ggplot2::theme_bw()
Unfortunately, you can't just load ggplot2 after loading ggtern (to avoid the masking issue) because ggtern loads ggplot2.
To see the difference in the code for each version of theme_bw() type the following in the console:
ggplot2::theme_bw
ggtern::theme_bw
UPDATE: The above clash between themes in ggplot2 and ggtern occurred in ggtern version 2.1.2 and earlier, but the clash no longer occurs in version 2.1.3, so all you need to do is update to the latest version of ggtern. See #NicolasHamilton's answer for full details.
I solved my problem by detaching ggtern.
detach("package:ggtern",unload=T)

knitr, RGL and legend3d: legend3d didn't show up in the html generated by knitr

I am able to create a dynamic 3D scatter plot using rgl and knitr, but the legend created by the legend3d is missing. I guess it may be related to the implementation of hook_webgl. Any idea? Thank you.
Here are the code I used to create the 3D scatter plot:
```{r fig1, webgl=TRUE, fig.width=10 , fig.height = 10}
library(knitr)
library(rgl)
knit_hooks$set(webgl = hook_webgl)
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
plot3d(x, y, z, col=rep(1:2,each=500))
legend3d("topright",legend=c("Type 1","Type 2"), pch=16, col=1:2)
```
My session info:
R version 3.1.3 (2015-03-09)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows Server 2008 R2 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 datasets methods
[7] base
other attached packages:
[1] knitr_1.11 rgl_0.95.1441 dplyr_0.4.3
loaded via a namespace (and not attached):
[1] assertthat_0.1 DBI_0.3.1 digest_0.6.8 evaluate_0.8
[5] formatR_1.2.1 highr_0.5.1 htmltools_0.3 lazyeval_0.1.10
[9] magrittr_1.5 parallel_3.1.3 R6_2.1.2 Rcpp_0.12.3
[13] rmarkdown_0.9.5 stringi_0.5-5 stringr_1.0.0 tools_3.1.3
[17] yaml_2.1.13
Looks like a bug in the rglwidget code; I'll look into it.
I recommend a few changes to your programming style. These won't help with this bug, but may save you problems later:
Use the setupKnitr() function rather than setting the knitr hook yourself. The link to knitr is likely to change, but setupKnitr() will protect you from problems.
Rather than saying webgl=TRUE in the chunk options, make a call to the rglwidget::rglwidget() function when you want to draw the plot. I'm hoping to make this call unnecessary in the future (more like what happens with regular plots), but for now it's the better tested way to do things.
Update your R. Current version is 3.2.3, with 3.2.4 due quite soon.
Use rgl and rglwidget from R-forge. They are newer than the CRAN versions, and have several bug fixes. Hopefully soon they'll have the legend bug fix too.
Added later:
This wasn't so much a bug as something that wasn't implemented. Now it is, if you use rgl version 0.95.1456 and rglwidget version 0.1.1456, both available from R-forge. Not much testing yet, so there may be more changes over the next while.

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

dev='png' is not working for pdf output in knitr

In the default setting, knitr will use "'pdf' for LaTeX output and 'png' for HTML/markdown". However, I can specify the dev = "png" in the chunk options for the LaTeX output. This feature is very useful to reduce the file size for big vector figure (e.g. maps).
In the previous version of knitr (could be 1.8.*, but not sure), I can specify the dev = "png" (the example below is working for earlier version).
Today I installed the latest version of knitr from github (just now). But the dev='png' is not working for pdf output. I have to use png device for pdf output as I have some big vector figure in pdf format.
The error message is:
Error in (function (filename = "Rplot%03d.png", width = 480, height = 480, :
unused argument (pdf = list(useDingbats = FALSE) Call: <Anonymous> ...
block_exec -> chunk_device -> dev_new -> do.call -> <Anonymous> Execution halted))
How could I fix this problem?
This is my example:
---
output: pdf_document
---
```{r, echo=FALSE, dev='png'}
plot(cars)
```
Thanks for any advice. Please let me know if my question is still not clear.
This is my session information.
R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.9.4
loaded via a namespace (and not attached):
[1] digest_0.6.4 evaluate_0.5.5 formatR_1.0 htmltools_0.2.6 rmarkdown_0.5.1 stringr_0.6.2
[7] tools_3.1.3 yaml_2.1.13
This is a bug in knitr. I just fixed it in the development version (v1.9.5). The reason for the failure was that the options for the pdf device were passed to the png device.

Resources