mdlincoln mdlincoln - 27 days ago 9
R Question

How to enforce stack ordering in ggplot geom_area

Is it possible to enforce the stack order when using

geom_area()
? I cannot figure out why
geom_area(position = "stack")
produces this strange fluctuation in stack order around 1605.

There are no missing values in the data frame.

library(ggplot2)

counts <- read.csv("https://gist.githubusercontent.com/mdlincoln/d5e1bf64a897ecb84fd6/raw/34c6d484e699e0c4676bb7b765b1b5d4022054af/counts.csv")

ggplot(counts, aes(x = year, y = artists_strict, fill = factor(nationality))) + geom_area()



Answer Source

You need to order your data. In your data, the first value found for each year is 'Flemish' until 1605, and from 1606 the first value is 'Dutch'. So, if we do this:

ggplot(counts[order(counts$nationality),], 
       aes(x = year, y = artists_strict, fill = factor(nationality))) + geom_area()

It results in

enter image description here

Further illustration if we use random ordering:

set.seed(123)
ggplot(counts[sample(nrow(counts)),], 
       aes(x = year, y = artists_strict, fill = factor(nationality))) + geom_area()

enter image description here