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

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.

Related

RStudio makes my graphs turn grey when I expand them

I'm using a script in RStudio which produces several graphs. This is a (very simplified) example of how it looks
mpg = mtcars$mpg
cyl = mtcars$disp
hp = mtcars $hp
plot(mpg, cyl)
dev.new()
plot(mpg,hp)
dev.new()
plot(hp, cyl)
When I run this in RStudio (using the "Source" key), the first graph stays in the "Plots" viewer in the lower right of the Rstudio window (I would actually like it to be a separate window as well if anyone knows how to do that), and the second and third graphs are produced as individual windows separate from the RStudio screen.
When I try to change the size of these windows (by pressing the full screen button in the top right corner, or by dragging the side), the most recently generated window is fine and resizes, but the previous one turns grey and the graph stops showing.
I thought it might have something to do with the fact that the graphics devices are inactive, but the most recently generated one, which rescales fine, also says it's inactive.
Any help would be appreciated! Thanks.
Edit: here is the output of sessionInfo():
> sessionInfo()
R version 4.0.0 (2020-04-24)
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 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] DescTools_0.99.36 dplR_1.7.1
loaded via a namespace (and not attached):
[1] Rcpp_1.0.4.6 mvtnorm_1.1-1 lattice_0.20-41 matrixStats_0.56.0 XML_3.99-0.3 png_0.1-7
[7] digest_0.6.25 MASS_7.3-51.5 R.methodsS3_1.8.0 grid_4.0.0 plyr_1.8.6 signal_0.7-6
[13] magrittr_1.5 stringi_1.4.6 rstudioapi_0.11 R.oo_1.23.0 R.utils_2.9.2 Matrix_1.2-18
[19] boot_1.3-24 tools_4.0.0 stringr_1.4.0 compiler_4.0.0 expm_0.999-4
It's not a perfect answer, but here's what I found to work around it:
When you generate a number of graphics devices the most recently generated one remains "active" while the rest are inactive. If you don't close the active window and resize the others, it works fine. But if you close the active window and then try to resize the others, they just go grey. Somehow, closing the active window shuts down something and stops you from being able to resize the graphs at all. Weird.

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.

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.

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)

how to display đ, ư, ơ, ă in R graphs

I am trying to put Vietnamese labeling in R graphs. I use RStudio and save my code using UTF-8 encoding. It handles the Vietnamese characters I put in the code well, I mean everything shows up in the code properly. However, in the graphs I make, while many characters display OK, several important ones do not show up properly, including
đ - which displays incorrectly as d
ư - which displays incorrectly as u
ơ - which displays incorrectly as o
ă - which displays incorrectly as a
Unfortunately this makes my graphs look unprofessional and untrustworthy.
I would really appreciate it if someone can help me figure this out.
Thanks much!
Trang
#DWin: I am on Windows 7, and here is my sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-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
loaded via a namespace (and not attached):
[1] MASS_7.3-17 MatchIt_2.4-20 tools_2.15.0
#krlmlr: Here's my code for a simple graph:
knorelative.count <- matrix(nrow=5,ncol=1)
knorelative.count[,1] <- c(1579,638,215,100,120)
par(mar=c(2,4,4,2))
barplot(prop.table(knorelative.count),beside=TRUE,
yaxt="n",ylim=c(0,.6),
legend=c("không ai biết",
"không biết nhiều hơn biết",
"nửa biết, nửa không biết",
"biết nhiều hơn không biết",
"tất cả đều biết"),
main="Người khác trong gia đình, họ hàng biết hay không")
axis(2,at=seq(0,.6,.1),labels=paste(100*seq(0,.6,.1),"%",sep=""),las=1)
When I run this, the đ in the main title and the two ơ's and the đ in the legend turn into d and o.
You are often safer specifying unicode characters by their hex codes:
plot(1:4,rep(1,4),pch=c("\u0111","\u01B0","\u01A1","\u0103"),cex=4)
For any Vietnamese folks out there who run into the same problem, here's an example for the fix using hex codes suggested by James:
print("trường")
[1] "truờng"
print("tr\u01B0ờng")
[1] "trường"
While I can type Vietnamese, in this example the word trường, into my R console ok, any kind of output (e.g. print, graph) fails to display the character ư. Replacing ư with the hex code fixes the output.
(Note: I used the function paste earlier, but then edited this based on James's suggestion to stick the hex code in the character string.)
I am so thankful to learn this way. I will do this for the report I am currently writing.
Trang
You save code in another file. Example: folder R/graph_display.R
After that run this code
eval(parse("R/graph_display.R", encoding = "UTF-8"))

Resources