Professional Documents
Culture Documents
Two Variables e
hjust, lineheight, size, vjust! h + geom_density2d()!
with ggplot2 Geoms - Use a geom to represent Continuous
+ geom_jitter(height = 2, width = 2)! x, y, alpha, colour, group, linetype, size!
Data Visualization
Basics
Cheat Sheet
Continuousxend = long + delta_long,
One Variable
a <- ggplot(mpg,
x, xend,
aes(hwy))
y, yend,
data points,
alpha, angle,
f <-
use the=geom’s
curvature
X, Continuous
color,
ggplot(mpg,
z))! aesthetic
curvature,
aes(cty, hwy))
Y
Two
properties to represent variables
Continuous
Variables
x, y, alpha,Bivariate Distribution
color, fill, shape,
h <- ggplot(movies, aes(year, rating))
size!
with ggplot2 a + geom_area(stat
linetype, size!
= "bin")
f + geom_blank() h + geom_bin2d(binwidth = c(5, 0.5)) h + geom_hex()!
ggplot2 é baseado na gramática de gráficos, a Continuous Continuous X, Continuous Y exmax,
+ geom_point()!
Continuous Bivariate Distribution
x, y, alpha, colour, fill, size
Cheat
ideia é que você possa Sheetqualquer gráfico
construir x, y,aalpha, color, fill, b + geom_path(lineend="butt", !
linetype,
<- ggplot(mpg, aes(hwy)) size f <- ggplot(mpg, aes(cty, hwy)) h <-
xmin, ymax, ymin, alpha, color, fill,
ggplot(movies,
linetype, size, weightaes(year, rating))
linejoin="round’,
b + geom_area(aes(y = ..density..), stat = "bin") linemitre=1)! x,geom_bin2d(binwidth
y, alpha, color, =fill, shape, size, stroke!
com alguns poucos componentes básicos: um ff++geom_jitter()
geom_blank() hh++geom_density2d() c(5, 0.5))
aa++geom_density(kernal
geom_area(stat = "bin") = "gaussian") x, y, alpha, color, fill, shape, size xmax,
x, y, xmin,
alpha, ymax,
colour, ymin, alpha,
linetype, size color, fill,
conjunto de dados, umBasics
conjunto de geoms— x,x,y,y,alpha,
alpha,color,
color,fill, x, y,
fill,linetype,
linetype, alpha,
size color, group, linetype, size!
size, weight
e linetype, size, weight
+ geom_quantile()! Função Contínua
marcações visuais que representam pontos de bb++geom_density(aes(y
geom_area(aes(y = ..density..), stat = "bin")
= ..county..))
ff++geom_point()
geom_jitter() hh++geom_hex()
geom_density2d()
a +geom_dotplot()
a+
b +=geom_polygon(aes(group
geom_density(kernal "gaussian") = group))! x,x,x, y, alpha,
y,y,alpha,
alpha,colour, color,
colour,fill group,
size size
linetype, linetype, size, weight! i <- ggplot(economics, aes(date, unemploy))
dados, e um sistema de coordenadas. x,x,y,y,alpha,
alpha,color,
color,fill,
fill,shape,
shape,size
size
Basics x,x,y,y,alpha,
alpha,color,
color,fill x, y,size,
fill, linetype, alpha,
weight color, fill, group, linetype, size!
F MA
+
4
2
=
4
2
aa+ geom_dotplot()
+ geom_freqpoly() !
b + geom_density(aes(y = ..county..)) ff++geom_quantile()
g + x,
Continuous Function
e x,+y, alpha,
geom_rug(sides
g <- ggplot(economics,
colour,aes(date,
y, alpha, color, linetype,
geom_area()
= "bl")!
fill size unemploy))
size!
i + geom_area()!
x, y, alpha, color, fill, linetype, size!
F MA ff++geom_rug(sides
geom_quantile()
14 14
= 2
plot
x,x,y,y,alpha,
alpha,color,
color,fill,
linetype, size!
sizesize, weight
linetype,
ge
g+++ geom_smooth(method
geom_line()
geom_area() = lm)!
x=F 1 system 1
ff++geom_smooth(model
geom_rug(sides = "bl")= lm) x,x,x,
y,y,alpha,
alpha,color,
color,linetype,
fill, size
linetype,
x, y, alpha, color, group, linetype, size!
y=A
0 0 bb++geom_histogram(aes(y
geom_freqpoly(aes(y ==..density..))
..density..))
x,alpha, color,
y, alpha, linetype,
color, size size, weight
fill, linetype,
y, alpha, color, fill,sizegroup, linetype, size, weight!
Para mostrar os valores
data dos dados, asplot
geom coordinate variáveis
0 1 2 3 4 0 1 2 3 4
b + geom_ribbon(aes(ymin=unemploy
a + geom_histogram(binwidth = 5) - 900,!
Discrete
ymax=unemploy
x, y, alpha, color, fill, linetype, size, weight + 900))! gg++geom_step(direction
geom_line() = "hv") i + geom_step(direction = "hv")!
são mapeadas x=F system ff++geom_text(aes(label
geom_smooth(model = lm)
F M Aparay = A propriedades estéticas do a <- ggplot(mpg, aes(fl)) = cty)) ex,x,+y,y,alpha,
geom_text(aes(label
alpha, color,linetype,
color, linetype,size
size = cty), nudge_x =
b + geom_histogram(aes(y x,= ymax,
..density..))ymin, alpha, color, fill, group, linetype,
C
4 4
1
coordinate
system
= 2
1
plot x, alpha, linetype, size, weight g <- ggplot(mpg, aes(class, hwy))
x, xend, y, yend, alpha, color, linetype, size! e + geom_crossbar(fatten
df <- data.frame(grp = =2)4:5, se = 1:2)
= c("A", "B"), fit df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)!
y=A g +Discrete
geom_bar(stat = "identity") x, y, ymax,
e <- ggplot(df, aes(grp,ymin,
fit, alpha,
ymin =color, fit-se,fill,
ymaxlinetype,
= fit+se))
color = F 0 0
X, Continuous Y j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
size = A 0 1 3 4 0 c <- ggplot(map, aes(long,
1 3
Graphical Primitives
2 4 a + geom_spoke(aes(yend
lat))
gx,<- = lat
y, ggplot(mpg,
alpha, + fill,
color, delta_lat,!
linetype, hwy))
size, weight size
Discreta X, Contínua Y
2
data geom coordinate plot aes(class,
x=F system c + geom_polygon(aes(group xend= group))= long + delta_long))! ee++geom_errorbar()
geom_crossbar(fatten = 2)
y=A
x, y,
x, y, alpha, color, fill, linetype, sizeangle, radius, alpha, gg++geom_boxplot()
color, linetype,
geom_bar(stat size
= "identity") x,x,ymax,f <- ggplot(mpg, aes(class, hwy))
y, ymax, ymin,
ymin, alpha,
alpha, color,
color, fill, linetype,
linetype, size,
color = F
size = A c <- ggplot(map, aes(long, lat)) lower, middle,
x, y, alpha, upper,
color, x, ymax, ymin,
fill, linetype, alpha,
size, weight size (also geom_errorbarh())
width j + geom_crossbar(fatten = 2)!
c + geom_polygon(aes(group = group)) color, fill, linetype, shape, size, weight ee++geom_linerange()
geom_errorbar() x, y, ymax, ymin, alpha, color, fill, group,
Construa um gráfico com ggplot() ou qplot(). x, y, alpha, color, fill, linetype, size gg++geom_dotplot(binaxis
geom_boxplot() = "y", f x,+ geom_bar(stat
x,ymin,
ymax, ymin,alpha,
ymax, alpha,color,
color,linetype,= "identity")!
linetype, size,
size
g <- ggplot(economics, aes(date, unemploy)) width geom_errorbarh())
linetype, size!
stackdir = "center")
lower, middle, upper, x, ymax, ymin, alpha, x, y,(alsoalpha, color, fill, linetype, size, weight!
ggplot(data = mpg, aes(x = cty, y = hwy))! g + geom_path(lineend="butt",
linejoin="round’, linemitre=1)
Uma variável
x,color, fill, linetype,
y, alpha, color, fillshape, size, weight e + geom_pointrange()
e + geom_linerange()
x,x,y,ymin,
ymin,ymax,
ymax,alpha,
alpha,color,
color,linetype,
fill, linetype, j + geom_errorbar()!
gg++geom_violin(scale
geom_dotplot(binaxis = "y",
= "area") size
Começa um gráfico que você termina adicionando camadas ga<- ggplot(economics, aes(date,
x, y, alpha, color, linetype, size
unemploy)) f shape,
+ geom_boxplot()!
size x, ymax, ymin, alpha, color, group, linetype,
x,stackdir
Contínuay, alpha,=color,
"center")
fill, linetype, size, weight
ele. Não temFvalores
M A padrões, mas permite maior controle do gg++geom_ribbon( geom_path(lineend="butt",
aes(ymin=unemploy - 900, x, y, alpha, color, fill e +x,geom_pointrange() size, width (also geom_errorbarh())!
que qplot().
4 4
y, lower, Maps middle, upper, ymax, ymin, alpha,
linejoin="round’+, 900)
ymax=unemploy linemitre=1)
) c <- ggplot(mpg, aes(hwy))
g + geom_violin(scale = "area") data <-x,color,
y, ymin, ymax, alpha,
data.frame(murder color, fill, linetype,
= USArrests$Murder,
fill, group, linetype, shape, size, weight!
!
3 3
x,
x,ymax,
y, ymin,
alpha, alpha,
color, color,
linetype, fill,
size linetype, size state shape,
= size
tolower(rownames(USArrests))) j + geom_linerange()!
dados
F MA
2
+ 2
= g + geom_ribbon(aes(ymin=unemployc + geom_area(stat - 900,
x, Discrete
y, alpha, color,
h <-=ggplot(diamonds,
"bin")!
fill, linetype,Ysize, weight
X, Discrete
aes(cut, color))
map <- map_data("state")
14 14
adiciona e <- ggplot(data, aes(fill Maps = murder)) x, ymin, ymax, alpha, color, group, linetype,
03 03 camadas com + ymax=unemploy + 900)) x, y, alpha, color, fill, linetype, size ! data
ef+ <-geom_map(
+ data.frame(murder
geom_dotplot(binaxis = USArrests$Murder,
= state), map = map) += "y", !
ggplot(mpg, aes(hwy,2 cty)) + 2 0 1 2 3 4 0 1 2 3 4 d<- ggplot(seals, aes(x = long, y = lat))
x, ymax, ymin, alpha, color, fill, linetype, size h + geom_jitter() aes(map_id
state = tolower(rownames(USArrests))) size!
data geom coordinate
geom_point(aes(color + = cyl)) 1 +
system
=
plotcamada = geom + x, y,
a + geom_area(aes(y = ..density..), stat = "bin")!
Discrete
alpha,
X,
color,
Discrete
fill, shape,
Y
size map expand_limits(
<- map_data("state")
stackdir x
= = map$long,
"center")! y = map$lat)
geom_smooth(method 0 ="lm")
coord_cartesian()
x=F
y=A
0 1 2 3 4
+ 0 1 0
2
stat padrão + d + geom_segment(aes(
mapeamentos
3 4
plotespecíficos da d<-
xend = long + delta_long,
ggplot(seals,
yend aes(x = long, y = lat))
= lat + delta_lat))
! h <- ggplot(diamonds,
h + geom_jitter()
x, y, alpha, color, fill,
aes(cut,
shape, size
color)) e <- ggplot(data,
map_id, alpha,
e + x,
Three Variablesf expand_limits(
+
y, alpha,
geom_map(
aes(fill
color,=fill,
geom_violin(scale
murder))
linetype, size
color,= state),
aes(map_id fill, map
x = map$long, y = map$lat
group!
= map) +
=) "area")!
j + geom_pointrange()!
x, y, ymin, ymax, alpha, color, fill, group,
scale_color_gradient() x=F
y=A
system +
camada
dx,+xend, c +linetype,
y, yend, alpha, color,
geom_segment(aes( geom_density(kernel
size = "gaussian")!
seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2)) i map_id, alpha, color, fill, linetype,
+ geom_raster(aes(fill size
= z), hjust=0.5,
linetype, shape, size
theme_bw() xend = long + delta_long,
d + geom_rect(aes(xmin =x,long, y, alpha, color,i <-fill, group, aes(long,linetype, x, y, alpha, color, fill, group, linetype, size,
elementos yend =long lat ++delta_lat))
ymin = lat, ggplot(seals, lat))size, weight! vjust=0.5, interpolate=FALSE)
xmax= delta_long, Three Variables x,weight
RStudio® é uma marca registrada da RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com! Aprenda mais em docs.ggplot2.org • ggplot2 2.0.0 • Atualizado: 03/16
Traduzido por Augusto Queiroz de Macedo • br.linkedin.com/in/augusto-queiroz-de-macedo-552b9822
Stats - An alternative way to build a layer Escalas Sistema de Coordenadas Facetas
Alguns gráficos realizam uma transformação nos dados As Escalas controlam como um gráfico mapeia os Facetas dividem um gráfico em sub-gráficos
r <- d + geom_bar()
originais. Use um stat para escolher uma transformação valores dos dados para os valores visuais de uma baseando-se em uma ou mais variáveis discretas.
comum para visualizar, e.g. a + geom_bar(stat = "count") estética. Para mudar o mapeamento, adicione uma r + coord_cartesian(xlim = c(0, 5))!
t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
escala personalizada. xlim, ylim!
fl cty cyl
x ..count..
4 4 n <- b + geom_bar(aes(fill = fl))! Sistema de coordenadas padrão! t + facet_grid(. ~ fl)!
3 3
n divide em colunas baseado em fl!
+ 2
= 2
lat
x, y, | ..count.., ..prop..! orientation=c(41, -74, 0))! t + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))
c + stat_density(adjust = 1, kernel = "gaussian")! Escala de local de X e Y projection, orientation, xlim, ylim! ↵c ↵d ↵e ↵p ↵r
x, y, | ..count.., ..density.., ..scaled.. Use com a estética x ou y (x exposto aqui) Mapeia projeções do pacote mapproj (mercator
long
t + facet_grid(. ~ fl, labeller = label_parsed)
(padrão), azequalarea, lagrange, etc.)
scale_x_date(date_labels = "%m/%d"), ! c d e p r
e + stat_bin_2d(bins = 30, drop = TRUE)! Distribuições 2D date_breaks = "2 weeks") - trata os valores de x como
x, y, fill | ..count.., ..density..! datas. Ver ?strptime para o formatos.!
e + stat_bin_hex(bins = 30)!
x, y, fill | ..count.., ..density..! scale_x_datetime() - trata os valores de x como data e Ajustes de Posição Rótulos
e + stat_density_2d(contour = TRUE, n = 100)! hora. Usa os mesmos argumentos que scale_x_date().! t + ggtitle("New Plot Title")!
Ajustes de posição definem como os geoms se
x, y, color, size | ..level..! scale_x_log10() - Transforma x para a escala log10.! Adiciona um título principal sobre o gráfico!
localizam, evitando que ocupem o mesmo espaço.
e + stat_ellipse(level = 0.95, segments = 51, type = "t")
.scale_x_reverse() - Inverte a direção do eixo x.! t + xlab("New X label")!
s <- ggplot(mpg, aes(fl, fill = drv)) Use funções scale
l + stat_contour(aes(z = z))! 3 Variáveis scale_x_sqrt() - Transforma x para a escala da raiz Muda o rótulo do eixo X! para atualizar o rótulo
quadrada de x. s + geom_bar(position = "dodge")! das legendas
x, y, z, order | ..level..!
Coloca os elementos lado a lado.!
t + ylab("New Y label")!
l + stat_summary_hex(aes(z = z), bins = 30, fun = mean)!
Muda o rótulo do eixo Y!
x, y, z, fill | ..value..! Escalas de Cor e Preenchimento s + geom_bar(position = "fill")!
l + stat_summary_2d(aes(z = z), bins = 30, fun = mean)! Empilha os elementos um sobre o outro,
t + labs(title =" New title", x ="New x", y ="New y") !
Discreta Contínua
x, y, z, fill | ..value.. normaliza a altura.! Todos acima
n <- d + geom_bar(! o <- c + geom_dotplot(! e + geom_point(position = "jitter")!
f + stat_boxplot(coef = 1.5)! Comparações aes(fill = fl)) aes(fill = ..x..))
x, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax..! Adiciona um ruído aleatório para as
f + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area")!
n + scale_fill_brewer(!
palette = "Blues") !
o + scale_fill_gradient(! posições X e Y de cada elemento Legendas
low = "red", ! A evitando a sobreposição.!
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. Para opções de paleta:! high = "yellow")
e + geom_label(position = "nudge")! n + theme(legend.position = "bottom")!
ibrary(RColorBrewer)! o + scale_fill_gradient2(! B
display.brewer.all() Afasta os rótulos dos pontos.! Coloca a legenda no "bottom", "top", "left", ou "right"!
e + stat_ecdf(n = 40)! low = "red", high = "blue",!
Funções mid = "white", midpoint = 25) n + guides(fill = "none")!
x, y | ..x.., ..y..! n + scale_fill_grey(!
s + geom_bar(position = "stack")!
o + scale_fill_gradientn(! Define o tipo da legenda para cada estética:
e + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), ! start = 0.2, end = 0.8, ! colours = terrain.colors(6)) ! Empilha os elementos um sobre o outro.
method = "rq")! na.value = "red") colorbar, legend, ou none (sem legenda) !
Também: rainbow(), heat.colors(),
x, y | ..quantile..! topo.colors(), cm.colors(),
Cada ajuste de posição pode ser redefinido como um n + scale_fill_discrete(name = "Title", !
e + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, ! RColorBrewer::brewer.pal() ajuste de posição manual dos argumentos width e labels = c("A", "B", "C", "D", "E"))!
fullrange = FALSE, level = 0.95)! height. Define o título da leganda e os rótulos com uma
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. Escalas de Formato
Manual Shape values s + geom_bar(position = position_dodge(width = 1)) função scale.
Manual shape values
p <- e + geom_point(aes(!
ggplot() + stat_function(aes(x = -3:3), ! Propósito Geral shape = fl, size = cyl))
0 6 12 18 24 0 0
100
count
.
ggplot() + stat_qq(aes(sample=1:100), distribution = qt, ! 3 9 15 21 | 50
Fundo branco com 50
t + coord_cartesian(!
p + scale_shape_manual(! r + theme_linedraw()!
o % linhas em grande!
0 0
5 11 17 23 O #
e + stat_sum()! expostos no gráfico à 100
Temas mínimos!
count
direita
50
50
c d e
fl
p r r + theme_void()!
e + stat_summary(fun.data = "mean_cl_boot")! Escalas de Tamanho 150
0 contraste
Mapeia para área do círculo c d e
fl
p r