data.frame에 두 개의 열이 있습니다.이 열은 동일한 순서로 정렬 된 레벨을 가져야하지만 간단하게하는 방법을 모르겠습니다.하나의 열에서 다른 열로 복사 인수 레벨 순서
library(ggplot2)
library(dplyr)
library(magrittr)
set.seed(1)
df1 <- data.frame(rating = sample(c("GOOD","BAD","AVERAGE"),10,T),
div = sample(c("A","B","C"),10,T),
n = sample(100,10,T))
# I'm adding a label column that I use for plotting purposes
df1 <- df1 %>% group_by(rating) %>% mutate(label = paste0(rating," (",sum(n),")")) %>% ungroup
# # A tibble: 10 x 4
# rating div n label
# <fctr> <fctr> <int> <chr>
# 1 BAD C 48 BAD (220)
# 2 BAD B 87 BAD (220)
# 3 BAD C 44 BAD (220)
# 4 GOOD B 25 GOOD (77)
# 5 AVERAGE B 8 AVERAGE (117)
# 6 AVERAGE C 10 AVERAGE (117)
# 7 AVERAGE A 32 AVERAGE (117)
# 8 GOOD B 52 GOOD (77)
# 9 AVERAGE C 67 AVERAGE (117)
# 10 BAD C 41 BAD (220)
# rating levels are sorted
df1$rating <- factor(df1$rating,c("BAD","AVERAGE","GOOD"))
ggplot(df1,aes(x=rating,y=n,fill=div)) + geom_col() # plots in the order I want
ggplot(df1,aes(x=label,y=n,fill=div)) + geom_col() # doesn't because levels aren't sorted
어떻게 다른 하나의 열에서 요소의 순서를 복사 관리 할 : 여기
상황입니까? 내가이 방식으로 작동 할 수 있지만 그것이 정말 어색한 것 같아요 :lvls <- df1 %>% select(rating,label) %>% unique %>% arrange(rating) %>% extract2("label")
df1$label <- factor(df1$label,lvls)
ggplot(df1,aes(x=label,y=n,fill=div)) + geom_col()
감사합니다.이 패키지는 흥미 롭습니다. 좀 더 자세한 접근법을 허용하는'fct_reorder' 함수를 발견했습니다 :'df1 $ label <- fct_reorder (df1 $ label, as.numeric (df1 $ rating))'. 어쩌면 당신의 대답에 그것을 추가 할 수 있을까요? –
감사합니다 - 할 것입니다! –