求助:使用ggplot绘图时,按population排序未生效的问题
问题描述
使用arrange函数对数据框按population排序后,ggplot绘图并未按照排序结果展示,x轴仍按country字母顺序排列,希望图表按population从小到大排列(人口最少的国家排在最前)。
原始代码:
data() pop <- population[population$year == 1995, ] pop <- pop[1:10, ] pop %>% ggplot(aes(x = country, y = population)) + geom_point() pop <- pop %>% arrange(population) pop %>% ggplot(aes(x = country, y = population)) + geom_point()
数据框内容:
country year population <chr> <int> <int> 1 Anguilla 1995 9807 2 American Samoa 1995 52874 3 Andorra 1995 63854 4 Antigua and Barbuda 1995 68349 5 Armenia 1995 3223173 6 Albania 1995 3357858 7 Angola 1995 12104952 8 Afghanistan 1995 17586073 9 Algeria 1995 29315463 10 Argentina 1995 34833168
解决方案
原因
arrange仅改变数据框的行顺序,但ggplot绘制x轴时,会默认按country的字符/因子水平顺序(字母顺序)排列,而非数据行的顺序。因此需要手动修改country的因子水平,使其按population排序。
方法1:修改数据框的因子水平
使用forcats包的fct_reorder函数,将country转换为按population排序的因子:
library(tidyverse) data(population) pop <- population[population$year == 1995, ] %>% slice(1:10) # 排序并重新设置country的因子水平 pop <- pop %>% arrange(population) %>% mutate(country = fct_reorder(country, population)) # 绘图 pop %>% ggplot(aes(x = country, y = population)) + geom_point()
方法2:直接在ggplot中指定排序
无需修改数据框,直接在aes里用fct_reorder设置x轴的排序规则:
pop %>% arrange(population) %>% ggplot(aes(x = fct_reorder(country, population), y = population)) + geom_point()
补充:反向排序(从大到小)
如果需要按人口从多到少排列,只需在排序变量前加desc():
# 方法1修改版 pop <- pop %>% arrange(desc(population)) %>% mutate(country = fct_reorder(country, desc(population))) # 方法2修改版 pop %>% ggplot(aes(x = fct_reorder(country, desc(population)), y = population)) + geom_point()
内容的提问来源于stack exchange,提问作者Julien
相关产品推荐
相关产品推荐

