首页 > 解决方案 > 如何使用 position_nudge 将 x 轴标签与 ggplot2 中的条形中心对齐

问题描述

在我的原始图中,最靠近 y 轴的条形与 y 轴重叠。我使用了 position_nudge 确实移动了条,但现在我无法将 x 轴标签与新定位的条对齐。未对齐的 x 轴标签的图片

# data frame
AV_sum <- data.frame(condition = c( "Braced", "Unbraced"), 
                     AvgVelocity = c(-1, -3), 
                     se = c( 0.5, 0.3)
                     )

p <- ggplot(AV_sum, aes(x =condition, y = abs(AvgVelocity), fill = condition)) + 
       ggtitle("Average Velocity Between Conditions")  + 
       geom_bar(position=position_nudge(0.5), colour = "black", stat="identity") + 
       geom_errorbar(aes(ymin=abs(AvgVelocity), ymax = abs(AvgVelocity)+se),
         width = 0.1,  colour = "black", position = position_nudge(0.5)) + 
       theme_classic() + xlab("Condition") + 
       ylab("Average Velocity") + 
       theme(plot.title = element_text(colour = 
         "black", size = 18, face = "bold", hjust = 0.5), legend.position= 
         "none", axis.text = element_text(colour = "black", size= 12, face = 
         "bold"), axis.title = element_text(size = 14, face = "bold"))

p +  
  scale_fill_manual(values = c( "white", "black")) + 
  coord_cartesian(ylim = c(0, 5), expand = FALSE) + 
  labs(fill = ("")) + 
  scale_y_continuous(breaks = seq(0, 5, 0.5)) + 
  geom_text(x = 2.0, y = 4, label = "***", size = 12)

标签: rggplot2

解决方案


我担心你用轻推使事情过于复杂。您的一个条与 y 轴发生碰撞的原因是由于expand = FALSEin coord_cartesian()

我最好的猜测是,您想防止条形图和 x 轴之间出现尴尬的间隙。如果是这种情况,我会建议调整expand内部的参数scale_y_continuous()

我已将您的代码重写为我认为您所追求的:

ggplot(AV_sum, aes(x =condition, y = abs(AvgVelocity), fill = condition)) + 
  ggtitle("Average Velocity Between Conditions")  + 
  # Deleted nudges, use geom_col, which is equivalent to geom_bar(stat = "identity")
  geom_col(colour = "black") + 
  geom_errorbar(aes(ymin=abs(AvgVelocity), ymax = abs(AvgVelocity)+se),
                width = 0.1,  colour = "black") + 
  geom_text(x = 1.5, y = 4, label = "***", size = 12) +
  # Moved expand from coord_cartesian to scale_y_condintuous
  coord_cartesian(ylim = c(0, 5)) +
  scale_x_discrete(name = "Condition") + 
  scale_y_continuous(breaks = seq(0, 5, 0.5), expand = c(0,0), name = "Average Velocity") + 
  scale_fill_manual(values = c( "white", "black")) + 
  theme_classic() + 
  theme(
    plot.title = element_text(colour = "black", size = 18, face = "bold", hjust = 0.5), 
    legend.position = "none", 
    axis.text = element_text(colour = "black", size= 12, face = "bold"), 
    axis.title = element_text(size = 14, face = "bold")
  )

在此处输入图像描述

关于 Tjebo 的评论,我通常发现构建 ggplot 代码最容易将执行类似操作的函数组合在一起,例如将几何图形组合在一起、组合坐标和(位置)比例以及组合主题调整。由于主题论点有时会变得庞大,我建议给每个论点单独一行。


推荐阅读