我对每个国家都有大约 1K 个观测值,我用facet_wrap来显示每个国家的geom_bar但输出是按字母顺序排列的。我想按偏斜对它们进行聚类或排序(因此最正偏的国家在一起并朝着正态分布国家移动,然后负偏的国家以最负偏的国家结束(,而不关注哪些国家彼此更相似。我在想也许psych::d escribe((可能有用,因为它计算偏斜,但我很难弄清楚如何将该信息添加到类似的问题中。
任何建议都会有所帮助
如果没有可重现的示例,我不能详细介绍太多细节,但这是我的一般方法。使用psych::describe()
创建从最正偏斜到最小正偏度排序的国家/地区向量:country_order
。接下来,使用country = factor(country, levels = country_order)
将数据集中的国家/地区列分解。使用facet_wrap
时,图将以与country_order
相同的顺序显示。
经过一些故障排除,我发现了(我认为是(一种有效的方法:
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