c("ggplot2")
wants <- wants %in% rownames(installed.packages())
has <-if(any(!has)) install.packages(wants[!has])
Data needs to be in long format.
50
Njk <- 3
P <- 2
Q <- rnorm(P*Q*Njk, mean=100, sd=15)
IQ <- rnorm(P*Q*Njk, mean=175, sd=7)
height <- sample(LETTERS[1:3], Njk*P*Q, replace=TRUE)
rating <- factor(rep(c("f", "m"), times=P*Njk))
sex <- factor(rep(c("control", "placebo", "treatment"), each=Q*Njk))
group <- interaction(sex, group)
sgComb <- data.frame(sex, group, sgComb, IQ, height, rating) myDf <-
Add a geom_point()
layer.
library(ggplot2)
ggplot(myDf, aes(x=height, y=IQ, colour=sex, shape=group))
pA1 <- pA1 + geom_point(size=3)
pA2 <-print(pA2)
Split the diagram into panels using facet_grid()
.
pA2 + facet_grid(. ~ group)
pA3 <- pA3 + ggtitle("IQ ~ height split by sex and group")
pA4 <- pA4 + guides(shape=FALSE)
pA5 <-print(pA5)
Add a geom_bar()
layer.
ggplot(myDf, aes(x=rating, group=sex, fill=sex))
pB1 <- pB1 + geom_bar(stat="bin", position=position_dodge())
pB2 <- pB2 + facet_grid(. ~ group)
pB3 <- pB3 + ggtitle("Rating frequencies by sex and group")
pB4 <-print(pB4)
Add a geom_histogram()
layer.
ggplot(myDf, aes(x=IQ, fill=group))
pC1 <- pC1 + geom_histogram()
pC2 <- pC2 + facet_grid(. ~ group)
pC3 <- pC3 + ggtitle("Histogram IQ by group")
pC4 <- pC4 + theme(legend.position="none")
pC5 <-print(pC5)
Add a geom_boxplot()
layer.
ggplot(myDf, aes(x=sex, y=height, fill=sex))
pD1 <- pD1 + geom_boxplot()
pD2 <- pD2 + facet_grid(. ~ group)
pD3 <- pD3 + ggtitle("Height by sex and group")
pD4 <- pD4 + theme(legend.position="none")
pD5 <-print(pD5)
geom_hline()
for a horizontal linegeom_vline()
for a vertical linegeom_smooth()
for a regression line including SEsgeom_text()
for text from a variableggtitle()
for a diagram titleannotate()
for text given directly as an argument ggplot(myDf, aes(x=height, y=IQ, colour=sex:group, shape=sex))
pE01 <- pE01 + geom_hline(aes(yintercept=100), linetype=2)
pE02 <- pE02 + geom_vline(aes(xintercept=180), linetype=2)
pE03 <- pE03 + geom_point(size=3)
pE04 <- pE04 + geom_smooth(method=lm, se=TRUE, size=1.2, fullrange=TRUE)
pE05 <- pE05 + facet_grid(sex ~ group)
pE06 <- pE06 + ggtitle("IQ ~ height split by sex and group")
pE07 <- pE07 + theme(legend.position="none")
pE08 <- pE08 + geom_text(aes(x=190, y=70, label=sgComb))
pE09 <- pE09 + annotate("text", x=165, y=130, label="annotation")
pE10 <-print(pE10)
See Cookbook for R: ggplot2
diagrams for many detailed examples of ggplot2
diagrams.
try(detach(package:ggplot2))
R markdown - markdown - R code - all posts