使用geom_point()避开位置,x =连续,y =因数

Del*_*eet 2 r ggplot2

我制作了一个函数,可以一次绘制来自多个因子分析的载荷,也可以绘制变量不完全重叠(或根本不重叠)的载荷。它可以正常工作,但有时因子负载在各个分析中都是相同的,这意味着这些点会相互绘制。

library(pacman)
p_load(devtools, psych, stringr, plotflow)
source_url("https://raw.githubusercontent.com/Deleetdk/psych2/master/psych2.R")

loadings.plot2 = function(fa.objects, fa.names=NA) {
  fa.num = length(fa.objects) #number of fas

  #check names are correct or set automatically
  if (length(fa.names)==1 & is.na(fa.names)) {
    fa.names = str_c("fa.", 1:fa.num)
  }
  if (length(fa.names) != fa.num) {
    stop("Names vector does not match the number of factor analyses.")
  }

  #merge into df
  d = data.frame() #to merge into
  for (fa.idx in 1:fa.num) { #loop over fa objects
    loads = fa.objects[[fa.idx]]$loadings
    rnames = rownames(loads)
    loads = as.data.frame(as.vector(loads))
    rownames(loads) = rnames
    colnames(loads) = fa.names[fa.idx]

    d = merge.datasets(d, loads, 1)
  }

  #reshape to long form
  d2 = reshape(d,
               varying = 1:fa.num,
               direction="long",
               ids = rownames(d))
  d2$time = as.factor(d2$time)
  d2$id = as.factor(d2$id)
  colnames(d2)[2] = "fa"

  print(d2)

  #plot
  g = ggplot(reorder_by(id, ~ fa, d2), aes(x=fa, y=id, color=time, group=time)) +
      geom_point(position=position_dodge()) +
      xlab("Loading") + ylab("Indicator") +
      scale_color_discrete(name="Analysis",
                           labels=fa.names)

  return(g)
}

#Some example plots    
fa1 = fa(iris[-5])
fa2 = fa(iris[-c(1:50),-5])
fa3 = fa(ability)
fa4 = fa(ability[1:50,])

loadings.plot2(list(fa1,fa1,fa2))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在这里,我两次绘制相同的对象只是为了显示效果。该图没有红色点,因为绿色的点fa.2在顶部。相反,我希望它们在y轴上避开。但是,position="dodge"使用各种设置似乎没有什么不同。

但是,position="jitter"它是可行的,但它是随机的,因此有时效果不佳,并使剧情混乱。

在此处输入图片说明

如何使点在y轴上避开?

goo*_*lim 6

显然,您只能侧身躲闪,但是有一种解决方法。诀窍是翻转x和y,执行position_dodge,然后执行coord_flip()。

  g = ggplot(data = reorder_by(id, ~ fa, d2), aes(x=id, y=fa, color=time, group=time)) +
    geom_point(position=position_dodge(width = .5)) +
    xlab("Loading") + ylab("Indicator") +
    scale_color_discrete(name="Analysis",
                         labels=fa.names) +
    coord_flip()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明