The following code worked in ggplot2 before I updated to version 2.2.0. Now I get Error: Aesthetics must be either length 1 or the same as the data (30): x, y, xend, yend. The error is caused by the two geom_segment calls.
drug1 <- c(.7, -1.6, -.2, -1.2, -.1, 3.4, 3.7, .8, 0, 2)
drug2 <- c(1.9, .8, 1.1, .1, -.1, 4.4, 5.5, 1.6, 4.6, 3.4)
d <- data.frame(Drug=c(rep('Drug 1', 10), rep('Drug 2', 10),
rep('Difference', 10)),
extra=c(drug1, drug2, drug2 - drug1))
ggplot(d, aes(x=Drug, y=extra)) +
geom_boxplot(col='lightyellow1', alpha=.3, width=.5) +
geom_dotplot(binaxis='y', stackdir='center', position='dodge') +
stat_summary(fun.y=mean, geom="point", col='red', shape=18, size=5) +
geom_segment(aes(x=rep('Drug 1', 30), xend=rep('Drug 2', 30), y=drug1, yend=drug2),
col=gray(.8)) +
geom_segment(aes(x='Drug 1', xend='Difference', y=drug1, yend=drug2 - drug1),
col=gray(.8)) +
xlab('') + ylab('Extra Hours of Sleep') + coord_flip()
Update: Improved code that works:
drug1 <- c(.7, -1.6, -.2, -1.2, -.1, 3.4, 3.7, .8, 0, 2)
drug2 <- c(1.9, .8, 1.1, .1, -.1, 4.4, 5.5, 1.6, 4.6, 3.4)
d <- data.frame(Drug=c(rep('Drug 1', 10), rep('Drug 2', 10),
rep('Difference', 10)),
extra=c(drug1, drug2, drug2 - drug1))
w <- data.frame(drug1, drug2, diff=drug2 - drug1)
ggplot(d, aes(x=Drug, y=extra)) +
geom_boxplot(col='lightyellow1', alpha=.3, width=.5) +
geom_dotplot(binaxis='y', stackdir='center', position='dodge') +
stat_summary(fun.y=mean, geom="point", col='red', shape=18, size=5) +
geom_segment(data=w, aes(x='Drug 1', xend='Drug 2', y=drug1, yend=drug2),
col=gray(.8)) +
geom_segment(data=w, aes(x='Drug 1', xend='Difference', y=drug1, yend=drug2 - drug1),
col=gray(.8)) +
xlab('') + ylab('Extra Hours of Sleep') + coord_flip()
drug1anddrug2are both length 10 . tryy=rep(drug1, 3)andyend=rep(drug2, 3))(I also think it would be nicer to add these to a second data frame rather than leaving ggplot to look in the global env)drug1anddrug2paired values (e.g. associated with the same subject)?