R GGPlot在facet之间重新排列变量

R GGPlot在facet之间重新排列变量,r,ggplot2,R,Ggplot2,我有一个数据框(长格式),其中包含来自个性自我报告的数据。我使用ggplot2绘制了我之前运行的探索性因素分析。下面,我创建了原始数据帧的一个子集 Dan Mirman博士提出了一种很好的方法来绘制这种数据,我很乐意这样做。所以,我修改了他的代码,但正如你从图片中看到的,情节有问题。y轴上的刻度按字母顺序倒序排列。然而,我想根据每个因素的负荷来订购这些天平。例如,我认为最好的顺序可能是第一个“A”和“IdP”,因为它们在因子1上有很强的负荷,然后是“R”,而“Ca”是因为它们在因子2上有负荷,“

我有一个数据框(长格式),其中包含来自个性自我报告的数据。我使用ggplot2绘制了我之前运行的探索性因素分析。下面,我创建了原始数据帧的一个子集

Dan Mirman博士提出了一种很好的方法来绘制这种数据,我很乐意这样做。所以,我修改了他的代码,但正如你从图片中看到的,情节有问题。y轴上的刻度按字母顺序倒序排列。然而,我想根据每个因素的负荷来订购这些天平。例如,我认为最好的顺序可能是第一个“A”和“IdP”,因为它们在因子1上有很强的负荷,然后是“R”,而“Ca”是因为它们在因子2上有负荷,“InP”是因为它在因子3上有负荷,而“Co”是因为它在因子4上有负荷。底部为“S”,因为它在多个刻度上显示相似的载荷

有人能帮我吗?我会非常感激的

library(ggplot2)
Scale <- c("A", "IdP", "R", "Ca", "S", "InP", "Co", "A", "IdP", "R", "Ca", "S", "InP", "Co", "A", "IdP", "R", "Ca", "S", "InP", "Co", "A", "IdP", "R", "Ca", "S", "InP", "Co")
Factor <- c("Factor1", "Factor1", "Factor1", "Factor1", "Factor1", "Factor1", "Factor1", "Factor2", "Factor2", "Factor2", "Factor2", "Factor2", "Factor2", "Factor2", "Factor3", "Factor3", "Factor3", "Factor3", "Factor3", "Factor3", "Factor3", "Factor4", "Factor4", "Factor4", "Factor4", "Factor4", "Factor4", "Factor4")
loading.db <- c(0.93, 0.71, -0.15,  0.00, 0.34, 0.08, 0.04, 0.02, 0.13, 0.79, 0.74, 0.43, 0.03, 0.06, -0.02, 0.30, -0.06, 0.25, 0.08, 0.66, -0.03, 0.09, -0.03, 0.18, -0.01, 0.37, -0.06, 0.62)

db <- data.frame(Scale, Factor, loading.db)

ggplot(db, aes(Scale, abs(loading.db), fill = loading.db)) + 
  facet_wrap(~ Factor, nrow = 1) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_fill_gradient2(name = "Loading", 
                       high = "green", mid = "white", low = "yellow", 
                       midpoint = 0, guide = F) +
  xlab("Test scales") + 
  ylab("Loading Strength") +
  theme_bw(base_size = 10)
库(ggplot2)

Scale您只需重新排序因子级别(使用
级别(db$Scale)
查看它们。例如,这里我通过查看哪些级别大于0.5(按因子1,…,4的顺序)对它们进行排序,然后添加在末尾缺失的级别(
S

0.5级])
lvls
lvls <- as.character(unique(db$Scale[db$loading.db > 0.5]))
lvls <- c(lvls, unique(levels(db$Scale)[!(levels(db$Scale) %in% lvls)]))

db$Scale <- factor(db$Scale, rev(lvls))

ggplot(db, aes(Scale, abs(loading.db), fill = loading.db)) + 
  facet_wrap(~ Factor, nrow = 1) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_fill_gradient2(name = "Loading", 
                       high = "green", mid = "white", low = "yellow", 
                       midpoint = 0, guide = F) +
  xlab("Test scales") + 
  ylab("Loading Strength") +
  theme_bw(base_size = 10)