ggtern disables some themes from ggplot2 - r

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)

Related

Scaling of plot in ggsave() different when RStudio plot pane is active

I cannot provide a reproducible example for this, but I wanted to ask about a curious behavior of the ggsave() function: I am experiencing the following:
I create a ggplot, by assigning a plot to a variable, let's say p
I evaluate p and - as it should be - the plot is displayed in the plot pane of RStudio.
My next call is ggsave(plot = p, filename = "plot.pdf"), the plot is
written to plot.pdf and R gives me the dimensions of the written plot on the console.
The strange thing is: When the RStudio plot pane is active (i.e. a RStudio graphics device is open), the dimensions of the plot written by ggsave() in step 3 are different than when no RStudio graphics device is open. Consequently, the scalings of the written plot are off. In other words: Step 3 produces different results depending on the execution of step 2. Does anyone know why this is the case? I thought that ggsave() is totally independent of any RStudio device. Or does this only happen on my machine?
This is my sessionInfo():
R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_2.2.1 scales_0.4.1 data.table_1.10.4
loaded via a namespace (and not attached):
[1] ggrepel_0.6.12 Rcpp_0.12.12 digest_0.6.12 grid_3.4.1 plyr_1.8.4 gtable_0.2.0 rlang_0.1.2 lazyeval_0.2.0
[9] labeling_0.3 RColorBrewer_1.1-2 tools_3.4.1 munsell_0.4.3 compiler_3.4.1 colorspace_1.3-2 sciplot_1.1-1 tibble_1.3.3
Expanding on Andrey Kolyadin's comment above...
From ggsave() documentation 'width, height Plot size in units ("in",
"cm", or "mm"). If not supplied, uses the size of current graphics
device.'
If we dig into the code behind ggsave, there's a snippet that says:
if (any(is.na(dim))) {
if (length(grDevices::dev.list()) == 0) {
default_dim <- c(7, 7)
}
else {
default_dim <- grDevices::dev.size() * scale
}
...
Which means that if the dimensions are not specified by the user:
if there's no active graphics device at all, default dimensions are 7 x 7;
if there's at least one active graphics device, use the dimensions of the last one (multiplied by scale, which defaults to 1).
RStudio's plot pane is a graphics device. So ggsave's behaviour differs depending on whether there's anything there.

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

ggmap missing background map (except when using pdf device)

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)

Legend with ggplot2 with geom="path" and alpha option

I'm a R user from way back but struggling to get my head around ggplot2. In this example, I cannot get a legend when I use the geom="path" option also with the alpha setting. If I set geom="point" it appears fine.
tmp <- data.frame(cx=rnorm(21),cy=rnorm(21),labels=c(rep("a",7),rep("b",7),rep("c",7)))
p1 <- qplot(data=tmp,cx,cy,geom="point",colour = labels, size=I(5), alpha=I(0.5))
Then the plot of points appears fine, including a legend with the correct alpha setting showing the dots. Adding in geom="path"
p2 <- qplot(data=tmp,cx,cy,geom="path",colour = labels, size=I(5), alpha=I(0.5))
Gets me a plot with the lines joined and correctly plotted with the alpha setting, and the legend also appears but is blank - eg. no alpha colors.
Is this possible to do?
It all works fine by dropping off the alpha parameter and I get solid colors in the plot and also the legend.
Update: Thanks for your comments so far but I guess this is just me or my setup as I still have this issue. An example of what I get in the link ...
http://i.stack.imgur.com/LiEwD.jpg
And for completeness...
> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: i386-pc-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C LC_TIME=English_United Kingdom.1252
attached base packages:
[1] grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] scales_0.2.1 ggplot2_0.9.1
loaded via a namespace (and not attached):
[1] colorspace_1.1-1 dichromat_1.2-4 digest_0.5.2 labeling_0.1 MASS_7.3-17 memoise_0.1
[7] munsell_0.3 plyr_1.7.1 proto_0.3-9.2 RColorBrewer_1.0-5 reshape2_1.2.1 stringr_0.6
[13] tools_2.15.0
I was finally able to reproduce what you are seeing, but only under very specific circumstances (and quite by accident that I happened to stumble across it). Given the circumstances, I'm pretty sure being on Windows (or rather, using the windows device driver) is necessary.
Using tmp, p1, p2 from the question:
dev.new()
p1
p2
The dev.new() is important so that you are starting with a fresh window (because something becomes corrupted later). These commands give appropriate plots (don't do anything with the plot window). Now, if you "scroll" (History -> Previous or Next) or resize window at this point, nothing is drawn in the legend boxes. Prior to doing that, can save and get the right legend. After doing that, saving (File -> Save as...), legend
boxes are blank. If you use the "scroll" option (I got it using the mouse wheel, repeatedly scrolling down, as I don't have recording on by default and therefore the Previous and Next options are grayed out), I (eventually) get the following on the console:
Error: VECTOR_ELT() can only be applied to a 'list', not a 'character'
which can be repeated some number of times before I eventually get:
Error: REAL() can only be applied to a 'numeric', not a 'character'
A workaround is to use ggsave. Since that creates a new device, you don't have to worry about the windows device getting into some broken state.
ggsave("tmp.jpg", p2)
I think the behavior I'm seeing is a bug in the windows graphics device.

Resources