How to ensure stack ordering in ggplot geom_area

Can stack order be applied when used geom_area()? I cannot understand why it geom_area(position = "stack")creates this strange fluctuation in order of the order of the order of 1605.

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()

+4
source share
3 answers

You need to order your details. In your data, the first value found for each year is “Flemish” until 1605, and since 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()

The result is

Further illustration if we use arbitrary ordering:

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

+10
source

randy, ggplot2 2.2.0 . , , . , , , scale_fill_manual() .

( ggplot John Colby)

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}
cols <- gg_color_hue(2)

ggplot(counts, 
   aes(x = year, y = artists_strict, fill = factor(nationality))) +
geom_area()+
scale_fill_manual(values=c("Dutch" = cols[1],"Flemish"=cols[2]),
   limits=c("Dutch","Flemish"))

ggplot(counts, 
   aes(x = year, y = artists_strict, fill = factor(nationality))) + 
geom_area()+
   scale_fill_manual(values=c("Dutch" = cols[1],"Flemish"=cols[2]),
   limits=c("Flemish","Dutch"))

counts$nationality <- factor(counts$nationality, rev(levels(counts$nationality)))
ggplot(counts, 
   aes(x = year, y = artists_strict, fill = factor(nationality))) + 
geom_area()+
   scale_fill_manual(values=c("Dutch" = cols[1],"Flemish"=cols[2]),
   limits=c("Flemish","Dutch"))
+1

it should do it for you

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

hope this helps

0
source

Source: https://habr.com/ru/post/1607676/


All Articles