I am trying to plot line graphs for and facet_wrap
for each dataset. What I would love to have is in light grey, transparent or something, all datasets in the background.
df <- data.frame(id=rep(letters[1:5], each=10),
x=seq(10),
y=runif(50))
ggplot(df, aes(x,y, group=id)) +
geom_line() +
facet_wrap(~ id)
This graph is how far I get, but I would love to have all the other missing 4 lines in each graph as well... In any way I try to use facet_wrap
, I get only the data of a single line.
What I would expect is something like this for each facet.
ggplot(df, aes(x,y, group=id)) +
geom_line() +
geom_line(data=df[1:10,], aes(x,y, group=id), size=5)
Here's another approach:
First add a new column identical to id:
df$id2 <- df$id
Then add another geom_line
based on the df without the original id column:
ggplot(df, aes(x,y, group=id)) +
geom_line(data=df[,2:4], aes(x=x, y=y, group=id2), colour="grey") +
geom_line() +
facet_wrap(~ id)
Here is an approach. It might not be suitable for larger datasets, as we replicate the data number_of_facets
-times.
First, we do some data-wrangling to create this desired dataframe. df$obs_id <- 1:nrow(df) #unique ID for each observation
#new data with unique ID's and 'true' facets
df2 <- expand.grid(true_facet=unique(df$id), obs_id=1:nrow(df))
#merge them
dat <- merge(df,df2,by="obs_id",all=T)
Then, we create a flag defining the 'true' faceted variable, and to discern background from foreground.
dat$col_flag <- dat$true_facet == dat$id
Now, plotting is easy. I've used geom_line twice instead of scales, as that was easier than to try to fix the ordering (would lead to black being plotted below grey).
p1 <- ggplot(dat, aes(x=x,y=y, group=id))+
geom_line(color="grey")+
geom_line(dat=dat[dat$col_flag,],size=2,color="black")+
facet_wrap(~true_facet)
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