首页 文章

级别因子分解无法转换为ggplot barplot变量顺序

提问于
浏览
2

我试图在ggplot堆积条形图中对变量进行排序 . 到目前为止,这是我的代码:

levels(rs$Site) <- c("Mature","Little East","Upper Fill","Lower Fill")
# I have rearranged the levels to the desired order, but the output looks like 
# c("Little East","Lower Fill","Upper Fill","Mature")

library(ggplot2)
library(scales)
ggplot(rs, aes(x = Site)) + geom_bar(aes(fill = At.Mature), position = 'fill') +
    scale_x_discrete(limits=unique(rs$Site)) +
    coord_flip()

但是,数据从上到下绘制为:

c("Mature","Upper Fill","Lower Fill","Little East")
# Notice this is simply a reverse of the output of the level reorder above

我尝试使用factor()重新排序级别,但结果保持不变 .

为什么“小东方”走向终点(图的底部)?我怎样才能解决这个问题?

1 回答

  • 2

    我们可以使用订单中指定的 levels 再次调用 factor

    rs$Site <- factor(rs$Site, levels = c("Mature", "Little East", 
              "Upper Fill", "Lower Fill"))
    

    并在 scale_x_discrete 中,使用 levels(rs$Site)

    ggplot(rs, aes(x = Site)) +  
          geom_bar(aes(fill = At.Mature), position = 'fill') + 
          scale_x_discrete(limits = levels(rs$Site)) + 
          coord_flip()
    

    数据

    set.seed(24)
    rs <- data.frame(Site = sample(c("Mature","Little East",
    "Upper Fill","Lower Fill"), 30, replace = TRUE), 
       At.Mature = sample(c("Yes", "No"), 30, replace = TRUE))
    

    分配 levels 是有风险的,因为它可以更改值,例如

    set.seed(24)
    v1 <- factor(sample(LETTERS[1:5], 20, replace = TRUE))
    v1
    #[1] B B D C D E B D E B D B D D B E A A C A
    #Levels: A B C D E
    levels(v1) <- c('C', 'D', 'E', 'A', 'B')
    v1
    #[1] D D A E A B D A B D A D A A D B C C E C  ### values got replaced
    #Levels: C D E A B
    

相关问题