如何在 ggplot2 的 position_dodge 中将单条位置与多条居中

How to centre single bar position with multiple bars in position_dodge in ggplot2

我有以下 geom_bar 闪避图,我认为 8、17、26 和 27 岁的单条看起来集中而不是偏左。我不确定要在脚本中添加什么来实现这一点。如有任何帮助,我们将不胜感激。

这是脚本:


ggplot(data = combo1, aes(x = Age_Year, fill = Tactic)) + 
    geom_bar(position = position_dodge(preserve = 'single')) + 
    theme_classic() + 
    labs(x = "Age (years)", y = "Counts of Fish", show.legend = FALSE)+
    theme(legend.position = "none")+
    scale_fill_manual("legend",  values = c("Migr" = "skyblue", "OcRes" = "pale green", "EstRes" = "pink"))
    

OP,用position_dodge2(preserve="single")代替position_dodge(preserve="single")。出于某种原因,居中 bars/columns 在 position_dodge() 中不能正常工作,但在 position_dodge2() 中可以。请注意,当您切换位置功能时,间距会略有不同,但总的来说应该可以解决您的问题。

OP 问题的可重现示例

library(ggplot2)
set.seed(8675309)
df <- data.frame(
  x=c("A", "A", "A", "B", "C", "C"),
  grouping_var = c("Left", "Middle", "Right", "Middle", "Left", "Right"),
  values = sample(1:100, 6))

position_dodge()的基本情节:

ggplot(df, aes(x=x, y=values, fill=grouping_var)) +
  geom_col(position=position_dodge(preserve = "single")) +
  theme_classic()

当您使用position_dodge2()时:

ggplot(df, aes(x=x, y=values, fill=grouping_var)) +
    geom_col(position=position_dodge2(preserve = "single")) +
    theme_classic()