Факторинг уровня не может быть преобразован в переменную порядка ggplot barplot - PullRequest
0 голосов
/ 26 мая 2018

Я пытаюсь упорядочить переменные в столбце с накоплением 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 Ответ

0 голосов
/ 26 мая 2018

Мы можем снова вызвать factor с levels, указанным в порядке

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

data

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