Building all the data in each face using facet_wrap and ggplot2

I am trying to build line graphs for and facet_wrap for each dataset. What I would like to have is light gray, transparent, or something else, 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) 

enter image description here

This graph is how far I get, but I would like everyone else to have 4 lines on each graph ... In any case, I try to use facet_wrap , I only get data from one line.

What I expect will be like this for every facet.

 ggplot(df, aes(x,y, group=id)) + geom_line() + geom_line(data=df[1:10,], aes(x,y, group=id), size=5) 

enter image description here

+5
source share
2 answers

Here's a different approach:

First add a new column identical to id:

 df$id2 <- df$id 

Then add another geom_line -based geom_line 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) 

enter image description here

+9
source

Here is the approach. It may not be suitable for large datasets, since we are replicating data number_of_facets -times.

First, we make some data enumeration attempts to create this required frame. df $ obs_id <- 1: nrow (df) #unique ID for each observation

 #new data with unique ID 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 determine the background from the foreground.

 dat$col_flag <- dat$true_facet == dat$id 

Now conspiracy is easy. I used geom_line twice instead of scales, as it was easier than trying to fix the order (it would cause black to be plotted below gray).

 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) 

enter image description here

+3
source

Source: https://habr.com/ru/post/1243564/


All Articles