Force geom_bar to not interfer with x ordering under any circumstances?
我正在尝试禁用
有没有办法将预先安排的 data.frame 传递到
例子
假设我们有一些数据已经按照应该绘制的方式排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | df <- structure(list(software = c("Python","R","SQL","Hadoop","Tableau", "Scala","SAS","Java","C","Spark"), users = c(6440, 5750, 4725,1755, 1660, 1560, 1490, 965, 875, 830)), row.names = c(NA, -10L), class ="data.frame") # software users # 1 Python 6440 # 2 R 5750 # 3 SQL 4725 # 4 Hadoop 1755 # 5 Tableau 1660 # 6 Scala 1560 # 7 SAS 1490 # 8 Java 965 # 9 C 875 # 10 Spark 830 df %>% ggplot(aes(software, users)) + geom_bar(stat ="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) |
这会重新排序
另外,jou 也可以简单地设置 x 轴的范围,这样你就不用再纠结于因素了:
1 2 3 4 | df %>% ggplot(aes(software, users)) + geom_col() + scale_x_discrete(limits = unique(df$software)) theme(axis.text.x = element_text(angle = 90, hjust = 1)) |
友情提示:
将其更改为因数,并根据出现情况对其进行排列。
1 2 3 4 5 6 7 | library(dplyr) library(ggplot2) df %>% mutate(software = factor(software, levels = unique(software))) %>% ggplot() + aes(software, users) + geom_bar(stat ="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) |
要重新排列而不将列更改为因子,我们可以使用
1 2 3 | ggplot(df) + aes(reorder(software, match(software,unique(software))), users) + geom_bar(stat ="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) |