Basically I'd like to create the first plot shown below in R using ggplot, but with both objects on the same graph (no facet wrapping).
Consider a minimal example that mimics my data structure:
library(reshape2)
library(ggplot2)
x <- seq(1, 5, length = 100)
y <- replicate(10, sin(2 * pi * x) + rnorm(100, 0, 0.3), "list")
z <- replicate(10, sin(2 * pi * x) + rnorm(100, 5, 0.3), "list")
y <- melt(y)
z <- melt(z)
df <- data.frame(x = y$Var1, rep = y$Var2, y = y$value, z = z$value)
dat <- melt(df, id = c("x", "rep"))
I can plot it with
ggplot(dat) + geom_line(aes(x, value, group = rep, color = variable),
alpha = 0.3) + facet_wrap(~variable)
And get
(source: carlboettiger.info)
But if I try dropping the facet wrapping, I thought it should group by color and variable, but instead the data are not broken out correctly, resulting in nonsense:
(source: carlboettiger.info)
ggplot2 can subset all data into groups and give each group its own appearance and transformation. In many cases new users are not aware that default groups have been created, and are surprised when seeing unexpected plots.
The function geom_point() adds a layer of points to your plot, which creates a scatterplot.
In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.
If you have a grouping variable you can create a scatter plot by group passing the variable (as factor) to the col argument of the plot function, so each group will be displayed with a different color.
The problem is that the group
aesthetic overrides the standard grouping protocols - it isn't included in the interaction of all discrete variables in the plot described in ?group
.
So, to get your plot to work without faceting you would need to manually specify the interaction
ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable), alpha = 0.3)
To override the alpha value in the aesthetic, use guide_legend(override.aes = ...))
. This information can be found following the links in ?guides
and specifically ?guide_legend
eg
ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable),
alpha = 0.3) +
scale_colour_discrete(guide = guide_legend(override.aes = list(alpha = 1)))
You could paste rep and variable a group:
ggplot(dat) + geom_line(aes(x, value, group = paste(variable, rep), color = variable),
alpha = 0.3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With