【问题标题】:ggplot2 draw graph with respect to a specific orderggplot2 根据特定顺序绘制图形
【发布时间】:2017-01-25 01:18:40
【问题描述】:

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

我想用 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)。我怎样才能做到这一点?

提前致谢!

【问题讨论】:

  • 如果省略 scale_manual,则顺序相同。
  • 或者,如果由于某种原因订单很重要。重新排序因子变量。像df$team &lt;- factor(df$team, levels = c("D", "B", "E", "A", "C")) 这样的东西。然后绘制它。
  • 如果你省略了 scale_manual 的 breaks 参数,那么顺序也是你想要的。我几乎永远无法判断此类异常是错误还是预期行为,因为 ggplot2 函数的帮助页面很少告诉我参数的可接受值或其影响。
  • 漏掉休息区只是给正确的顺序,但情节还是一样的,这意味着情节本身是错误的。

标签: r ggplot2


【解决方案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 )

【讨论】:

  • 我相信你是对的,但是在我的机器上,ggplot2 仍然给我同样的结果。
猜你喜欢
  • 1970-01-01
  • 2012-04-10
  • 2018-05-30
  • 1970-01-01
  • 2015-11-13
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
相关资源
最近更新 更多