Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

position_stack

Stack overlapping objects on top of one another.


Description

position_fill additionally standardises each stack to have unit height.

Usage

position_fill()

position_stack()

See Also

See geom_bar and geom_area for more examples.

Examples

# Stacking is the default behaviour for most area plots:
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar()
# Fill makes it easier to compare proportions
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar(position = "fill")

# To change stacking order, use factor() to change order of levels
mtcars$vs <- factor(mtcars$vs, levels = c(1,0))
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar()

ggplot(diamonds, aes(price, fill = cut)) +
  geom_histogram(binwidth = 500)
# When used with a histogram, position_fill creates a conditional density
# estimate
ggplot(diamonds, aes(price, fill = cut)) +
  geom_histogram(binwidth = 500, position = "fill")

# Stacking is also useful for time series
data.set <- data.frame(
  Time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
  Type = rep(c('a', 'b', 'c', 'd'), 4),
  Value = rpois(16, 10)
)

ggplot(data.set, aes(Time, Value)) + geom_area(aes(fill = Type))

# If you want to stack lines, you need to say so:
ggplot(data.set, aes(Time, Value)) + geom_line(aes(colour = Type))
ggplot(data.set, aes(Time, Value)) +
  geom_line(position = "stack", aes(colour = Type))

# But realise that this makes it *much* harder to compare individual
# trends

animint2

Animated Interactive Grammar of Graphics

v2020.9.18
GPL-3
Authors
Toby Hocking [aut, cre] (Original animint code), Hadley Wickham [aut] (Forked ggplot2 code), Winston Chang [aut] (Forked ggplot2 code), RStudio [cph] (Forked ggplot2 code), Nicholas Lewin-Koh [aut] (hexGrob), Martin Maechler [aut] (hexGrob), Randall Prium [aut] (cut_width), Susan VanderPlas [aut] (Animint GSOC 2013), Carson Sievert [aut] (Animint GSOC 2014), Kevin Ferris [aut] (Animint GSOC 2015), Jun Cai [aut] (Animint GSOC 2015), Faizan Khan [aut] (Animint GSOC 2016-2017), Vivek Kumar [aut] (Animint GSOC 2018), Himanshu Singh [aut] (Animint2 GSoC 2020)
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.