Skip to content

Instantly share code, notes, and snippets.

@vheaffinitech
Last active December 16, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vheaffinitech/5465519 to your computer and use it in GitHub Desktop.
Save vheaffinitech/5465519 to your computer and use it in GitHub Desktop.
Graphiques en R avec ggplot2
#ggplot2 + plyr pour manipuler les données
install.packages(c("ggplot2","plyr"))
#Récupération de données :
install.packages("gcookbook")
library(ggplot2)
#test
qplot(mtcars$wt, mtcars$mpg)
#dataset inclu :
str(diamonds)
# simple
ggplot(diamonds, aes(x=cut)) + geom_bar()
ggplot(diamonds, aes(x=carat)) + geom_bar()
ggplot(diamonds, aes(x=carat)) + geom_bar(binwidth = 0.1)
ggplot(diamonds, aes(x=cut,y=carat)) + geom_bar(stat="identity")
ggplot(diamonds, aes(x=cut,y=carat,fill=color)) + geom_bar(stat="identity", position="dodge")
ggplot(diamonds, aes(x=cut,y=carat,fill=color)) + geom_bar(stat="identity", position="dodge") + scale_fill_brewer(palette="Pastel1")
#remplissage
ggplot(diamonds, aes(x=cut,y=carat,fill=color)) + geom_bar(stat="identity", position="fill")
#il faut trier avant
diam <- diamonds[with(diamonds,order(color)),]
ggplot(diam, aes(x=cut,y=carat,fill=color)) + geom_bar(stat="identity", position="fill")
#histogrammes
ggplot(diamonds, aes(x=carat)) + geom_histogram()
ggplot(diamonds, aes(x=carat)) + geom_histogram(binwidth=diff(range(diamonds$carat))/20)
#histo + facettes + mise en variable des objets de base
plt <- ggplot(diamonds,aes(x=carat)) +geom_histogram()
plt
plt + facet_grid(cut ~.)
plt + facet_grid(cut ~., scales="free_y")
plt + facet_grid(cut ~ clarity)
plt + facet_grid(cut ~ clarity, scales="free_y")
#lignes
ts <- data.frame(c(1:20),rnorm(20))
names(ts) <- c("time","val")
ggplot(ts, aes(x=time,y=val)) + geom_line()
ggplot(ts, aes(x=time,y=val)) + geom_line() + geom_point()
#points
ggplot(diamonds, aes(x=carat, y=price,colour=clarity)) + geom_point(shape=21,size=1.5)
ggplot(diamonds, aes(x=carat, y=price,colour=clarity, shape=cut)) + geom_point(size=1.5)
ggplot(diamonds, aes(x=carat, y=price,colour=clarity, shape=cut)) + geom_point(size=1.5) + stat_smooth(method=lm)
ggplot(diamonds, aes(x=carat, y=price)) + geom_point(shape=21,size=1.5)+ stat_smooth(method=lm)
#heatmaps
str(AirPassengers)
AirPassengers
#transformer la TS en Dataframe
AirPass <- data.frame(vol = as.numeric(AirPassengers), an = as.numeric(floor(time(AirPassengers))),mois = as.numeric(cycle(AirPassengers)))
#créer la heatmap
ggplot(AirPass, aes(x=an,y=mois,fill=vol)) + geom_tile() + scale_x_continuous(breaks=seq(1949,1960,by=1)) + scale_y_continuous(breaks=seq(12,1))
#sauvegarde dans des fichiers
ggsave("fich.pdf",width=20,height=8,units="cm")
ggsave("fich.svg",width=20,height=8,units="cm")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment