ggplot2

Rafael Catoia

18 de abril de 2016

ggplot2

Tópicos

Como instalar e Carregar

#install.packages(ggplot2)
library(ggplot2)
#install.packages("dplyr")
library(dplyr)
#install.packages("ggthemes")
library(ggthemes)
#install.packages("maps")
library(maps)
#install.packages("ggExtra")
library(ggExtra)
library(knitr)
dados= mpg
conjunto= iris

Sintaxe

Fazer gráficos do ggplot2 podem parecer um pouco complicados no começo. Isso porque ele possui uma sintaxe um pouco diferente dos plots “normais”.

A primeira coisa a se fazer quando se utiliza o ggplot é mapear.

ggplot(conjunto,aes())

O que vai no eixo x?

O que vai no eixo y?

Tamanho dos elementos?

Forma dos elementos?

Cor dos elementos?

Após definido o terreno, adicionamos as formas:

+geom_bar() +geom_jitter() +geom_boxplot() +geom_density() +geom_density2d() +etc..

E como adicionar título? +ggtitle(“Novo título”)

Como adicionar legenda nos eixos? +xlab(“Legenda X”) +ylab(“Legenda y”)

Como mudar a legenda? + guides(fill=guide_legend(title=“New Legend Title”))

Como mudar a posição da legenda? +theme(legend.position=“bottom”) ou “Top” ou c(x,y)

Gráficos de Barra

ggplot(dados,aes(as.factor(cyl)))+geom_bar()

ggplot(dados,aes(as.factor(cyl)))+
geom_bar(color="deepskyblue",size=1,fill="deepskyblue4",alpha=0.5)

ggplot(dados,aes(x=as.factor(cyl),fill=as.factor(year)))+geom_bar()

ggplot(dados,aes(x=as.factor(cyl),fill=year))+geom_bar()+facet_wrap(~year)

ggplot(dados,aes(as.factor(year),fill=as.factor(cyl)))+geom_bar()

ggplot(dados,aes(as.factor(cyl),fill=as.factor(year)))+geom_bar()+ggtitle("Contagem de carros com diferentes número de cilindros")+xlab("Número de Cilindros") + ylab("Contagem")+theme(legend.position="bottom")

theme_set(theme_bw(base_size = 18))
ggplot(dados,aes(as.factor(cyl),fill=as.factor(year)))+geom_bar()+
  ggtitle("Contagem de carros com diferentes número de cilindros")+
  xlab("Número de Cilindros") + ylab("Contagem")+theme(legend.position="bottom")+ 
  theme(legend.text = element_text(face = "bold")) + guides(fill=guide_legend(title="New Legend Title"))+scale_fill_brewer(palette="Set1")

Gráficos de Pontos

dados$year=as.factor(dados$year)
dados$cyl=as.factor(dados$cyl)

ggplot(dados,aes(year,displ))+geom_jitter()

ggplot(dados,aes(year,displ))+geom_jitter(width = 0.4,size=5,color="red")

ggplot(dados,aes(year,displ,color=year))+geom_jitter(width=0,size=4)+coord_flip()

ggplot(dados,aes(year,displ,color=cyl))+geom_jitter(size=4,width = 0.2)+ scale_colour_brewer(palette="Spectral")

ggplot(dados,aes(year,displ,color=cyl))+geom_jitter(size=4,width = 0.2)+ scale_colour_brewer(palette="BrBG") #OrRd,Dark2,BrBG

ggplot(dados,aes(year,displ,color=cyl,shape=drv))+geom_jitter(size=4,width = 0.2,alpha=0.8)+ scale_colour_brewer(palette="BrBG")

a=ggplot(dados,aes(year,displ,color=cyl))+geom_jitter(size=4,width = 0.2,alpha=0.5)+geom_boxplot(color="black",alpha=0.3,width=0.4)

a+coord_flip()

dados2=dados
dados2=dados2 %>% mutate(categoria=cty/2)
dados2$categoria=ifelse(dados2$categoria<9,1,0)
dados2$categoria=as.factor(dados2$categoria)

ggplot(dados2,aes(year,displ,color=cyl))+geom_jitter(size=4,width = 0.2,alpha=0.5)+geom_boxplot(color="black",alpha=0.4,width=0.5)+facet_grid(~categoria)

Gráficos de Dispersão

ggplot(dados,aes(x=displ,y=hwy))+geom_point()

ggplot(dados,aes(x=cty,y=hwy,size=displ,shape=year,color=class))+geom_point(alpha=0.5)

ggplot(dados,aes(x=cty,y=hwy,size=displ,shape=year,color=class))+geom_point(alpha=0.5)+facet_wrap(~cyl)

ggplot(dados,aes(x=cty,y=hwy,size=displ,color=class,shape=year))+geom_point(alpha=0.5)+ scale_colour_brewer(palette="OrRd")

# Utilizando o Conjunto Iris

ggplot(conjunto,aes(x=Sepal.Length,Sepal.Width))+geom_point()

ggplot(conjunto,aes(x=Sepal.Length,Sepal.Width,size=Petal.Length,color=Petal.Width,shape=Species))+geom_point(alpha=0.8)

ggplot(conjunto,aes(x=Sepal.Length,Petal.Length,size=Sepal.Width,color=Petal.Width))+geom_point(alpha=0.8)+ theme_stata()

ggplot(conjunto,aes(x=Petal.Length,Petal.Width,size=Sepal.Length,color=Sepal.Width))+geom_point(alpha=0.8)+theme_economist()

ggplot(conjunto,aes(x=Petal.Length,Petal.Width,size=Sepal.Length,color=Sepal.Width))+geom_point(alpha=0.8)+facet_wrap(~Species)

Densidades

ggplot(dados,aes(displ))+geom_density()

ggplot(dados,aes(displ))+geom_density(adjust=0.2)

ggplot(dados,aes(displ))+geom_density(adjust=3)

ggplot(dados,aes(displ,color=year))+geom_density()

ggplot(dados,aes(displ,color=year))+geom_density(alpha=0.7,fill="white",size=1)+ scale_colour_brewer(palette="Set1")

ggplot(dados,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)

dados5=dados %>% filter(cyl!=5)

ggplot(dados5,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)

theme_set(theme_minimal())

ggplot(dados5,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)

theme_set(theme_classic())

ggplot(dados5,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)

theme_set(theme_economist())

ggplot(dados5,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)

ggplot(dados5,aes(displ,fill=year))+geom_density(alpha=0.4,color="black")+facet_wrap(~cyl)+theme_hc()+ scale_colour_hc()

Densidades Bivariadas

theme_set(theme_bw(base_size = 16))
ggplot(conjunto,aes(x=Sepal.Length,y=Sepal.Width))+geom_point()+geom_density2d()

ggplot(conjunto,aes(x=Petal.Length,y=Petal.Width,size=Sepal.Length,color=Sepal.Width))+geom_point()+
  stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE,alpha=0.8)

p <- ggplot(conjunto,aes(x=Petal.Length,y=Petal.Width,size=Sepal.Length,color=Sepal.Width,shape=Species)) + geom_point()
p

ggExtra::ggMarginal(p, type = "density")

Mapas

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
crimesm <- reshape2::melt(crimes, id = 1)
if (require(maps)) {
  states_map <- map_data("state")
  ggplot(crimes, aes(map_id = state)) +
    geom_map(aes(fill = Murder), map = states_map) +
    expand_limits(x = states_map$long, y = states_map$lat)

  last_plot() + coord_map()
  ggplot(crimesm, aes(map_id = state)) +
    geom_map(aes(fill = value), map = states_map) +
    expand_limits(x = states_map$long, y = states_map$lat) +
    facet_wrap( ~ variable)
}

Histogramas

ggplot(dados,aes(displ))+geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(dados,aes(displ))+geom_histogram(binwidth = 0.4,color="black",fill="red")

ggplot(dados,aes(displ,color=cyl,fill=cyl))+geom_histogram(binwidth = 0.6,alpha=0.8)+facet_wrap(~year)

ggplot(dados,aes(displ))+geom_histogram(binwidth = 0.6,color="black",fill="red")+ theme_calc()+ scale_colour_calc()+facet_wrap(~year+cyl)

Violin Plot

theme_set(theme_bw(base_size = 16))

ggplot(conjunto,aes(Species,Petal.Length))+geom_violin()

ggplot(conjunto,aes(Species,Petal.Length))+geom_violin(draw_quantiles = c(0.25, 0.5, 0.75),fill="deepskyblue")

ggplot(conjunto,aes(Species,Petal.Length,fill=Species,color=Species,shape=Species))+geom_jitter(size=3)+
  geom_violin(draw_quantiles = c(0.25,0.5,0.75),alpha=0.5)

ggplot(conjunto,aes(Species,Petal.Length,fill=Species,color=Species,shape=Species))+
  geom_jitter(size=3,color="black",width = 0.5,alpha=0.7)+geom_violin(draw_quantiles = c(0.25,0.5,0.75),alpha=0.5,color="black",size=0.7)

ggplot(dados2,aes(categoria ,displ,fill=categoria,shape=categoria))+
  geom_jitter(alpha=0.8,size=3)+ geom_violin(alpha=0.5,draw_quantiles = c(0.25,0.5,0.75),size=0.7,color="black")+
  facet_wrap(~year)+theme_tufte()