facet_wrap内按偏斜排序直方图

问题描述 投票:0回答:2

我对每个国家/地区都有大约一千个观测值,并且我使用facet_wrap显示了每个国家/地区的geom_bar,但是输出是按字母顺序排列的。我想按偏斜对它们进行聚类或排序(因此,最正偏斜在一起,并向正态分布国家移动,然后向以负偏斜结尾的负偏斜国家移动),而无需关注哪些国家与哪个更相似彼此。我在想psych :: describe()可能有用,因为它可以计算偏斜,但是我很难弄清楚如何实现将这些信息添加到similar question

任何建议都会有所帮助

r sorting ggplot2 distribution facet-wrap
2个回答
1
投票

如果没有可复制的示例,我不能做太多细节,但这将是我的一般方法。使用psych::describe()创建一个国家矢量,其从最大正偏度到最小正偏度排序:country_order。接下来,使用country = factor(country, levels = country_order)分解数据集中的国家/地区列。当您使用facet_wrap时,绘图将以与country_order相同的顺序显示。


0
投票

经过一些故障排除后,我发现(我认为是)一种有效的方法:

skews <- psych::describe.By(df$DV, df$Country, mat = TRUE) #.BY and mat will produce a matrix that you can use to merge into your df easily
skews %<>%select(group1, mean, skew) %>% sjlabelled::as_factor(., group1) #Turn it into a factor, I also kept country means 
combined <- sort(union(levels(df$Country), levels(skews$group1))) #I was getting an error that my levels were inconsistent even though they were the same (since group1 came from df$Country) which I think was due to having Country reference category Germany which through off the alphabetical sort of group1 so I used [dfrankow's answer][1]
df <- left_join(mutate(df, Country=factor(Country, levels=combined)),
                mutate(skews, Country=factor(group1, levels=combined))) %>% rename(`Country skew` = "skew", `Country mean` = "mean") %>% select(-group1) 

df$`Country skew` <- round(df$`Country skew`, 2)
ggplot(df) +
  geom_bar(aes(x = DV, y=(..prop..)))+ 
  xlab("Scale axis text") + ylab("Proportion") +
  scale_x_continuous()+
  scale_y_continuous(labels = scales::percent_format(accuracy = 1))+

  ggtitle("DV distribution by country mean")+ 
  facet_wrap(~ Country %>% fct_reorder(.,mean), nrow = 2) #this way the reorder that was important for my lm can remain intact
© www.soinside.com 2019 - 2024. All rights reserved.