ggplot2:如何在将条形图保持在相同位置的同时更改点图的位置

ggplot2: How to change the position of a point plot while keep the bar plot in the same position

我想用一个包含点、线和条的图来绘制配对 t 检验的结果,就像纸上的图一样(Belmund,等人。绘制人类外侧内嗅皮质中的序列结构。Elife, 8. doi:10.7554/eLife.45333).

查看剧情截图:

在我的实践中,很容易将 geom_pointgeom_linegeom_bar 放在同一个图中,但是当我尝试更改点和线,同时保持条形不变。

我尝试在点图中使用 position_dodge(),但是,它会移动图中的所有元素。有任何想法吗?感谢您的帮助!

library(ggplot2)

id <- rep(c(1:29), times = 2)
condition <- c(rep('vector.angle', times = 29), rep('baseline', times = 29))
value <- rnorm(58, mean = 22, sd = 27)
v.angle.gg <- data.frame(id, condition, value)

ggplot(data = v.angle.gg, aes(x = condition, y = value)) +
  geom_hline(aes(yintercept = 0), color = "black", size = 1.5, linetype = 14) + 
  stat_summary(fun.y = mean, geom = "bar", aes(x = condition, y = value, fill = condition), 
               width = 0.3, position = position_identity()) + 
  geom_line(aes(group= id), size = 1, color = 'gray') + 
  geom_point(size = 4, position = position_dodge(width= 1)) +
  scale_fill_brewer(palette="Paired") +
  xlab('Conditions') + ylab('Parameter Estimations') +
  theme(
    title = element_text(size=rel(1.3),face="bold", colour = "black"), 
    axis.line.x = element_line(size = 1, colour = "black"),
    axis.text.x=element_text(size=rel(1.3),face="bold", colour = "black"),
    axis.ticks.x = element_line(size=rel(2), colour = "black"),
    axis.line.y = element_line(size = 1, colour = "black"),
    axis.text.y=element_text(size=rel(1.3),face="bold", colour = "black"),
    axis.ticks.y = element_line(size=rel(2), colour = "black"),
    panel.border = element_blank(),
    panel.background = element_blank(),
    panel.grid = element_blank()
  ) + 
  guides(fill=F,color=F) 

问题求思路,这里有攻略

条形图以连续整数 x 绘制条形图,在本例中为 c(1, 2)。所以你需要在 c(1.2, 1.8) 处连接它们的点和线。现在,在数据集中,列 condition 首先具有按字母顺序排列的较大值,并且它们将在绘图之前被强制分解。因此,新的 x 坐标向量将正确地成为 condition 的子集。不清楚?

f <- v.angle.gg$condition
f <- c(1.2, 1.8)[as.integer(factor(f))]

这些是新坐标。并且必须在 geom_linegeom_point 中设置它们。现在更有意义了吗?希望如此。
我简化了图表,以便只绘制相关部分。

ggplot(data = v.angle.gg, aes(x = condition, y = value)) +
  geom_hline(aes(yintercept = 0), color = "black", size = 1.5, linetype = 14) + 
  stat_summary(fun = mean, geom = "bar", aes(x = condition, y = value, fill = condition), 
               width = 0.3, position = position_identity()) + 
  geom_line(aes(x = f, group= id), size = 1, color = 'gray') + 
  geom_point(aes(x = f), size = 4, position = position_dodge(width= 1))