R ggplot2根据特定顺序绘制图形

R ggplot2根据特定顺序绘制图形,r,ggplot2,R,Ggplot2,如果重复,请向我指出原始问题 我想使用ggplot2在R中绘制一个图形,下面的代码显示了我想要实现的目标 require(ggplot2) require(data.table) set.seed(1) dat <- data.table(time = rep(c(1:40), times = 5), value = runif(200), team = rep(c("A","B","C","D","E"), e

如果重复,请向我指出原始问题

我想使用ggplot2在R中绘制一个图形,下面的代码显示了我想要实现的目标

require(ggplot2)
require(data.table)

set.seed(1)

dat <- data.table(time = rep(c(1:40), times = 5),
                  value = runif(200), 
                  team = rep(c("A","B","C","D","E"), each = 40))
dat[, value := value / sum(value), by = .(time)]

ggplot(dat, aes(x = time, y = value, group=team, fill=team)) +
geom_area(position = "fill") +
scale_fill_manual(values = c("red","blue","green","pink","yellow"),
                  breaks = c("D", "B", "E", "A", "C"),
                  labels = c("D", "B", "E", "A", "C"))
require(ggplot2)
要求(数据表)
种子(1)

dat这几乎是

geom_area
按区域首次出现在数据中的顺序堆叠区域

按适当的顺序排序
dat
似乎可以解决您的问题

# create order you want
my_order <- c("D", "B", "E", "A", "C")
# reversed to get correct ordering in data table
dat[, order := match(team, rev(my_order))]
# sort the data.table
setorder(dat, time, order)
# make the  plot
ggplot(dat, aes(x = time, y = value, fill=team))+
  geom_area(position = "fill") +
  scale_fill_manual(values = c("red","blue","green","pink","yellow"),
                    breaks = my_order ,
                    labels = my_order )
#创建您想要的订单

我的订单如果你不看磅秤手册,订单是一样的。或者,如果订单出于某种原因很重要。对因子变量重新排序。类似于
df$team的内容如果您在scale_手册中省略
breaks
参数,那么顺序也是您想要的。我几乎无法判断这些异常是错误还是预期行为,因为ggplot2函数的帮助页面很少告诉我参数的可接受值或其影响。省去中断只需给出正确的顺序,但绘图仍然是一样的,这意味着绘图本身是错误的。我相信你是正确的,但在我的机器上,ggplot2仍然提供相同的结果。