使用 ggmosaic 和 geom_mosaic() 在 R 中的马赛克图中重新排序因子

问题描述

我尝试熟悉如何使用 ggmosaic 包的 geom_mosaic() 命令在 R 中制作马赛克图。

我的问题是,我希望按照每个地区老年人的份额对地区进行排序,而不是像现在这样按名称排序。有什么帮助吗?

我不太习惯使用因子,但我尝试用 forecat 的 fct_reorder() 命令做不同的事情,但没有任何运气。

这是一个示例数据集(不是我使用的实际数据集)和我迄今为止编写的代码

# install.packages(c("ggplot2","ggmosaic"))
library(ggplot2)
library(ggmosaic)
  
# Make data set      
region <- c("oslo","oslo","Viken","nordland","nordland")
age    <- c("young","adult","senior","young","senior")
pop    <- c(145545,462378,89087,299548,729027,223809,52156,136872,51317)
df     <- data.frame(region,age,pop)

# Make mosaic plot
ggplot(data = df) +
  geom_mosaic(aes(x = product(age,region),fill = age,weight = pop)) +
  coord_flip() +
  theme_minimal()

更新: 对不起,如果我不清楚,但我想要的是这个:

mosaic plot ranked

区域按照老年人的份额而不是认顺序进行排名/排序,如下所示:

mosaic plot unranked

我通过以“不整洁”的方式使用 fct_reorder() 命令而不是作为管道中 mutate 命令的一部分以某种方式解决了它。我不知道为什么这意味着任何区别。另一条评论,fct_reorder() 命令在常规 ggplot2 geom_... 命令中工作正常,但在 ggmosaic 包中的 geom_mosaic 命令中(至少我尝试过的方式)不行。

代码(太冗长,无法估计老年人的份额)

# install.packages(c("ggplot2","ggmosaic"))
library(ggplot2)
library(ggmosaic)

# Make data set      
region <- c("oslo",pop)

df <- df %>% 
  group_by(region,age) %>%
  summarise(pop = sum(pop)) %>% 
  mutate(senior = case_when(age == "senior" ~ pop))

# Get total population of each region
df_tot <- df %>% 
  group_by(region) %>% 
  summarise(poptot = sum(pop),senior = median(senior,na.rm = TRUE)) %>% 
  mutate(senior_share = senior / poptot * 100) %>% 
  select(region,senior_share)

# Estimate senior share of each region
# Change order of regions
df <- df %>% 
  left_join(df_tot,by = "region") #%>% 

# Fix the factors
df$region <- fct_reorder(df$region,df$senior_share)
df$age <- factor(df$age,levels = c("young","senior"))

# Make mosaic plot
ggplot(data = df) +
  geom_mosaic(aes(x = product(age,weight = pop)) +
  coord_flip() +
  theme_minimal()

解决方法

使用此代码,设置序列,

df$age <- factor(df$age,levels = c("senior","adult","young"))