ggplot2 Episode II

Ксения Власова
18/10/14

Refresh grammar

Элементы ggplot2

  • Массив данных (data)
  • Схема соответствия переменных из массива визуальным средствам (aesthetic)
  • Геометрический объект (geom)
  • Статистическое преобразование (stat)
  • Координатная система (coord)
  • Ориентиры (guide)
  • Панели (facet)
  • Художественное оформление (theme)

Refresh grammar. Exemple

ggplot(data = cars, aes(x = speed, y = dist)) + geom_point()

plot of chunk unnamed-chunk-2

ggplot(data = cars, aes(x = speed, y = dist)) + stat_identity()

plot of chunk unnamed-chunk-3

Layer Style

ggplot(data = cars, aes(x = speed)) + geom_bar()+ coord_polar()+ theme_bw()

plot of chunk unnamed-chunk-4

Different visual tools

ggplot(data = cars, aes(x = speed, y = dist, color = speed, size = dist)) + geom_point()

plot of chunk unnamed-chunk-5

Legends

mustache <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
mustache

plot of chunk unnamed-chunk-6

Hiding the title or removing the legend

mustache + guides(fill=guide_legend
(title=NULL))

plot of chunk unnamed-chunk-7

mustache+theme (legend.position="none")

plot of chunk unnamed-chunk-8

Modifying the text of legend titles and labels

mustache + scale_fill_discrete(name="Experimental\nCondition",
breaks=c("ctrl", "trt1", "trt2"),labels=c("Control", "Treatment 1", "Treatment 2"))

plot of chunk unnamed-chunk-9

Changing the position

mustache + theme(legend.position="top")

plot of chunk unnamed-chunk-10

Another way

Position legend in graph, where x, y is 0,0 (bottom left) to 1,1 (top right)

mustache + theme(legend.justification=c(1,0), legend.position=c(1,0))

plot of chunk unnamed-chunk-11

Titles

mustache + ggtitle("Plant growth")

plot of chunk unnamed-chunk-12

mustache + ggtitle("Plant growth with\ndifferent treatments") + theme(plot.title = element_text(lineheight=.8, face="bold"))

plot of chunk unnamed-chunk-13

Background color

mustache + theme(plot.background = element_rect(fill = "coral1"))

plot of chunk unnamed-chunk-14

Scale for shapes, aka glyphs

diamonds <- diamonds[sample(nrow(diamonds), 100), ]
(d <- qplot(carat, price, data=diamonds, shape=cut))

plot of chunk unnamed-chunk-15

d + scale_shape(solid = TRUE)

plot of chunk unnamed-chunk-15

d + scale_shape(name="Cut of diamond")

plot of chunk unnamed-chunk-15

Facets

library(reshape2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
sp + facet_wrap( ~ day, ncol=2)

plot of chunk unnamed-chunk-16

Modifying facet label appearance

sp + facet_grid(sex ~ day) +
    theme(strip.text.x = element_text(size=8, angle=75),
          strip.text.y = element_text(size=12, face="bold"),
          strip.background = element_rect(colour="red", fill="#CCCCFF"))

plot of chunk unnamed-chunk-17

References