简体   繁体   English

ggplot(geom_bar)不根据数值对y轴进行排序

[英]ggplot (geom_bar) not sorting y-axis according to numeric values

I am trying to sort y-axis numerically according to population values.我正在尝试根据总体值对 y 轴进行数字排序。 Have tried other stackoverflow answers that suggested reorder/ converting columns to numeric data type (as.numeric), but those solutions does not seem to work for me.尝试过其他建议将列重新排序/转换为数字数据类型(as.numeric)的 stackoverflow 答案,但这些解决方案似乎对我不起作用。

Without using reorder, the plot is sorted alphabetically:不使用重新排序,plot 按字母顺序排序: 在此处输入图像描述

Using reorder, the plot is sorted as such:使用重新排序,plot 排序如下: 在此处输入图像描述

The code i am using:我正在使用的代码:

library(ggplot2)
library(ggpubr)
library(readr)
library(tidyverse)
library(lemon)
library(dplyr)

pop_data <- read_csv("respopagesextod2011to2020.csv")
temp2 <- pop_data %>% filter(`Time` == '2019')
ggplot(data=temp2,aes(x=reorder(PA, Pop),y=Pop)) +  geom_bar(stat='identity') + coord_flip()

How should I go about sorting my y-axis?我应该如何 go 关于排序我的 y 轴? Any help will be much appreciated.任何帮助都感激不尽。 Thanks!谢谢!

I am using data filtered from: https://www.singstat.gov.sg/-/media/files/find_data/population/statistical_tables/singapore-residents-by-planning-areasubzone-age-group-sex-and-type-of-dwelling-june-20112020.zip我使用的数据来自: https://www.singstat.gov.sg/-/media/files/find_data/population/statistical_tables/singapore-residents-by-planning-areasubzone-age-group-sex-and-type -of-dwelling-jun-20112020.zip

The functions are all working as intended - the reason you don't see the result as expected is because the reorder() function is specifying the ordering of the pop_data$PA based on each observation in the set, whereas the bars you are plotting are a result of summary statistics on pop_data .这些功能都按预期工作-您没有按预期看到结果的原因是因为reorder() function 正在根据集合中的每个观察值指定pop_data$PA的排序,而您正在绘制的条形图是pop_data的汇总统计结果。

The easiest solution is to probably perform the summarizing first, then plot and reorder the summarized dataset.最简单的解决方案可能是先执行汇总,然后是 plot 并重新排序汇总数据集。 This way, the reordering reflects an ordering of the summarized data, which is what you want.这样,重新排序反映了汇总数据的排序,这是您想要的。

temp3 <- pop_data %>% filter(`Time` == '2019') %>%
  group_by(PA) %>%
  summarize(Pop = sum(Pop))

ggplot(data=temp3, aes(x=reorder(PA, Pop),y=Pop)) +
  geom_bar(stat='identity') + coord_flip()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM