如何在ggplot geom_area中强制执行堆栈排序

mdl*_*oln 4 r ggplot2

使用时是否可以强制执行堆栈顺序geom_area()?我无法弄清楚为什么geom_area(position = "stack")在1605左右的堆栈顺序中产生这种奇怪的波动.

数据框中没有缺失值.

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()
Run Code Online (Sandbox Code Playgroud)

Her*_*oka 10

您需要订购数据.在您的数据中,每年找到的第一个值是"佛兰芒",直到1605年,从1606开始,第一个值是"荷兰语".所以,如果我们这样做:

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

它导致了

在此输入图像描述

如果我们使用随机排序进一步说明:

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

在此输入图像描述