如果重复,请指出我原来的问题。
我想使用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"))
ggplot2输出:
如您所见,图形的顺序与图例的顺序不匹配。它是A,B,C,D,E的顺序,但不是D,B,E,A,C。我想在顶部绘制粉红色的图形,然后是蓝色,然后是黄色,然后是红色,然后是绿色(DBEAC)。我怎样才能做到这一点?
提前致谢!
答案 0 :(得分:1)
这几乎与ggplot2: Changing the order of stacks on a bar graph,
重复 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 )