r - 水平分解无法转换为 ggplot barplot 变量顺序

标签 r ggplot2 graph scale geom-bar

我正在尝试对 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() 重新排序级别,但结果保持不变。

为什么“小东”会移向末尾(图的底部)?我该如何解决这个问题?

最佳答案

我们可以使用顺序中指定的级别再次调用因子

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))

分配级别是有风险的,因为它可能会更改值,例如

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

关于r - 水平分解无法转换为 ggplot barplot 变量顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539583/

相关文章:

r - 如何在 R 包的 html 帮助页面中显示新闻?

r - 尝试使用 RSelenium chromedriver 时出现连接拒绝错误

r - R 中与 ggridges 重叠的线

r - 如何更改 ggplot 中的一个特定方面

r - 镜像直方图,有代码但担心其丢弃数据?

r - 如何在R中将变量“labeled”的类更改为字符串或chr?

r - 从多个 URL 自动下载,处理反馈对话框/cookie

r - 哑铃图: Order and value label

python - 有效地使用图形工具

减少 ggnet2 网络图中的空白空间