Reputation: 35
I am trying to overlay two plots with different variable treament (from the same dataset) :
- the first one with a mutate
and reorder
(to make a geom_boxplot + geom_jitter
) ;
- the second one with a group_by
and summarize
(to make a geom_line
). Both of them have to be overlayed.
When I try the following code, this Error is given : Aesthetics must be either length 1 or the same as the data (4): label
Local <- c("A", "B", "C", "D", "A", "B", "C", "D")
Case <- c("QQ", "DD", "GG", "PP", "QQ", "DD", "GG", "PP")
Div <- c(2, 4, 5, 1, 3, 5, 6, 7)
dat <- data.frame(Local, Case, Div)
p1 <- dat %>%
mutate(Loc = reorder(Local, Div, FUN = median)) %>%
ggplot(aes(Loc, Div, label = Case)) +
geom_boxplot(outlier.size = -1) +
geom_jitter(width = 0.1, alpha = 1, aes(color = Case, size = Div)) +
geom_text_repel()
dat %>%
group_by(Local) %>%
summarise(Div = mean(Div)) %>%
mutate(Loc = reorder(Local, Div, FUN = median)) %>%
ggplot(aes(Loc, Div, group = 1)) +
geom_line()
p1 + geom_line (data = dat %>%
group_by(Local) %>%
summarise(Div = mean(Div)) %>%
mutate(Loc = reorder(Local, Div, FUN = median)), aes(Loc, Div, group = 1))
The first plot gives :
And the second one :
But how to overlay them ?
Upvotes: 0
Views: 172
Reputation: 725
datBox <- dat %>%
mutate(Loc = reorder(Local, Div, FUN = median))
datLine <- dat %>%
group_by(Local) %>%
summarise(Div = mean(Div)) %>%
mutate(Loc = reorder(Local, Div, FUN = median)) %>%
mutate(LocNum = recode(Loc, A = "1", D="2", B="3", C="4"))
ggplot(data = datBox, aes(Loc, Div)) +
geom_boxplot(outlier.size = -1) +
geom_jitter(width = 0.1, alpha = 1, aes(color = Case, size = Div)) +
geom_text_repel(aes(label = Case)) +
geom_line(data =datLine, aes(as.numeric(LocNum),Div))
I made a secondary axis with numeric values corresponding to the order of the Loc
factor. geom_line
does not appreciate the factor in axis. There is propably more elegant solutions. Also I inserted label
in the geom_text_repel
aes
Upvotes: 1