在ggplot中反转geom_density顺序

时间:2018-06-19 14:22:36

标签: r ggplot2

# OUR REPRODUCIBLE EXAMPLE
library(tidyverse)
ggplot(diamonds, aes(price, fill = cut)) +
  geom_density(bins = 50, stat = "bin", alpha = 0.3)

上面是使用 count 代替 density 的不错的密度图。就像我想要的,几乎

我还想反转菱形cut因子的顺序,因此ideal因子移至图的后部,而fair因子移至图的后部。我从其他StackOverflow问题中提出的解决方案均无用。正确的解决方法是什么?

# DOESNT APPEAR TO CHANGE ANYTHING
library(forcats)
ggplot(diamonds, aes(price, fill = cut), fct_rev(cut)) +
  geom_density(bins = 50, stat = "bin", alpha = 0.3)

#JUST SCREWS UP THE Y SCALE
ggplot(diamonds, aes(price, fill = cut)) +
  geom_density(bins = 50, stat = "bin", alpha = 0.3) + 
  scale_y_discrete(limits = rev(levels(diamonds$cut)))

# JUST TOTALLY WRONG
ggplot(diamonds, aes(price, fill = cut)) +
  geom_density(
    bins = 50, stat = "bin", 
    alpha = 0.3, 
    position = position_fill(reverse = TRUE)
  )

1 个答案:

答案 0 :(得分:4)

如果您在fct_rev()中应用aes(),则应该获得所需的输出。

ggplot(diamonds, aes(price, fill = fct_rev(cut))) +
  geom_density(bins = 50, stat = "bin", alpha = 0.3)

enter image description here