library(ggplot2) ## Exercise 1 nb_cyl <- as.factor(mtcars$cyl) ggplot(mtcars,aes(x=disp,y=mpg, colour=nb_cyl))+ geom_point() ## Exercise 2 X <- seq(-2*pi,2*pi,by=0.1) n <- length(X) D <- data.frame(x=rep(X,2), type=c(rep("sine",n),rep("cosine",n)),f=c(sin(X),cos(X))) ggplot(D,aes(x=x,y=f,colour=type))+ geom_line()+ geom_hline(yintercept=-1,size=2, colour="blue")+ geom_hline(yintercept=1,size=2, colour="blue")+ theme(legend.position="none")+ facet_wrap(~type) ## Exercise 3 n <- 100 x <- runif(n) y <- 3+x+rnorm(n,sd=0.2) D <- data.frame(x=x,y=y) model.reg <- lm(y~x,data=D) D <- data.frame(x=x, y=y, yhat=model.reg$fitted.values) ggplot(D,aes(x=x,y=y))+ geom_point()+ geom_segment(data=D, aes(x=x, y=y, xend=x, yend=yhat), color="red", alpha=0.5)+ geom_abline(intercept=model.reg$coefficients[1],slope=model.reg$coefficients[2], color="blue")+ theme_classic() ## Exercise 4 data(state) states <- data.frame(state.x77,state.name=rownames(state.x77), state.region=state.region) q1 <- quantile(states$Income,1/3,names=FALSE) q2 <- quantile(states$Income,2/3,names=FALSE) states$revenu1 <- cut(states$Income,breaks=c(min(states$Income),q1,q2,max(states$Income)),labels=c("low","medium","high"),include.lowest=TRUE) ggplot(states,aes(x=Population,y=Murder))+ geom_smooth(method="lm",se=FALSE)+ geom_point(aes(colour=state.region), size=0.3)+ facet_wrap(~revenu1)+ theme(axis.text.x = element_text(angle = 30))