首页 文章

GGPlot在方面之间重新排序变量

提问于
浏览
1

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

Here,Dan Mirman博士提出了一种绘制这类数据的好方法,我想这样做 . 所以,我已经调整了他的代码,但正如你从图像中看到的那样,情节有一个问题 . y轴上的刻度按字母顺序反向排序 . 但是,我想根据每个因素的负荷来订购这些尺度 . 例如,我认为最好的顺序可能是"A"和"IdP",因为它们在Factor1上加载,然后"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)

Plot Factor loadings

1 回答

  • 1

    你只需要重新排序你的因子水平(见 levels(db$Scale) . 例如,我在这里通过查看哪些大于0.5(按因子1,...,4的顺序)对它们进行排序,然后添加那些最后遗漏了(在这种情况下是 S ) .

    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)
    

    enter image description here

相关问题