![](/img/trans.png)
[英]How can I change the order (categories) of my bar charts in ggplot2? and flip my legend?
[英]ggplot2: how to sort the categories in horizontal bar charts?
我很難找到正確的方法在ggplot中整理文本x
軸。 考慮以下簡單示例:
library(ggplot2)
library(dplyr)
dataframe <- data_frame('group' = c(1,1,1,2,2,2),
'text' = c('hello', 'world', 'nice', 'hello', 'magic', 'bug'),
'count' = c(12,10,3,4,3,2))
> dataframe
# A tibble: 6 × 3
group text count
<dbl> <chr> <dbl>
1 1 hello 12
2 1 world 10
3 1 nice 3
4 2 hello 4
5 2 magic 3
6 2 bug 2
現在是圖表
ggplot(dataframe, aes(x = text, y = count, fill = count, group = group)) +
geom_bar(stat = 'identity') +
facet_wrap(~ group, scales = "free_y") +
coord_flip()
問題是:我想按遞增count
順序對單詞進行排序,以使計數最高的單詞出現在每個類別的底部。
使用ggplot2條形圖和ggplot條形圖中的順序條中 具有與面相關的類別順序的解決方案無濟於事。
我懷疑這是與水平傾斜有關的問題。 例如,使用
ggplot(dataframe, aes(x = reorder(text, -count), y = count, fill = count, group = group)) +
geom_bar(stat = 'identity') +
facet_wrap(~ group, scales = "free_y") +
coord_flip()
僅排序一張圖表(在右側)。
有任何想法嗎? 謝謝!
> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.5.0 ggplot2_2.2.1
loaded via a namespace (and not attached):
[1] Rcpp_0.12.9 digest_0.6.12 assertthat_0.1 grid_3.3.2 plyr_1.8.4
[6] R6_2.2.0 gtable_0.2.0 DBI_0.5-1 magrittr_1.5 scales_0.4.1
[11] lazyeval_0.2.0 labeling_0.3 tools_3.3.2 munsell_0.4.3 colorspace_1.3-2
[16] tibble_1.2
我刪除了一些無用的部分,例如組,使用了' geom_col()
,但技巧可能是按每個因子級別sum
,而不是mean
,這是reorder
的默認設置。 一致地使用tidyverse函數通常可以使您免於令人不快的意外,即使reorder
也可以在這里進行。
library(tidyverse)
dataframe %>%
mutate(text = text %>% forcats::fct_reorder(count, sum)) %>%
ggplot(aes(x = text, y = count, fill = count)) +
geom_col() +
facet_wrap(~ group, scales = "free_y") +
coord_flip()
請記住,因子只有一種排序,這意味着,如果您相應地處理數據,則可以在兩個方面進行相反的排序(即,每個方面afaik都沒有排序)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.