5

With the code below the labelling in facet bB is not correctly positioned. The problem seems to originate from the fact that there is no position_dodge(preserve="single") for geom_text (correct?). I am aware that I could 'manually' add an empty dummy cell (filling y=0 in facet bB), but I was wondering whether there is any way to correct for it in ggplot directly?

v1 <- LETTERS[1:2]
v2 <- letters[1:2]
v3 <- c("x","y")
g <- expand.grid(v1,v2,v3)
val=c(sample(10,8))
df<- data.frame(g,val)
df<- df[-8,]


    df %>% ggplot() +
      geom_bar(aes(x=Var2, y=val, fill=Var3, group=Var3), 
               stat="identity", 
               position=position_dodge(preserve="single"))+
      geom_text(aes(x=Var2, y=val+1, label=val, group=Var3), 
                position=position_dodge(width=1))+
  facet_grid(Var1~Var2, scale="free_x")

enter image description here

Update/answer: using position_dodge2 alignes the bar with the labelling (however, the bar is the then centered and not aligned with the bars in the other facets).

df %>% ggplot() +
  geom_bar(aes(x=Var2, y=val, fill=Var3, group=Var3), stat="identity", 
           position=position_dodge2(preserve="single"))+
  geom_text(aes(x=Var2, y=val+1, label=val, group=Var3), 
            position=position_dodge2(width=1))+
  facet_grid(Var1~Var2, scale="free_x")
Tung
  • 26,371
  • 7
  • 91
  • 115
zoowalk
  • 2,018
  • 20
  • 33

1 Answers1

0

If the example is similar to your actual use case, I suggest avoiding all this trouble with position_dodge, and simply assign different variables to the x-axis & columns of facet_grid instead. You are currently using "Var2" for both.

ggplot(df, 
       aes(x = Var3, y = val)) +              # put Var3 here instead of Var2
  geom_col(aes(fill = Var3)) +                # dodge becomes unnecessary here
  geom_text(aes(y = val + 1, label = val)) +  # as above
  facet_grid(Var1 ~ Var2) +

  # optional, simulates the same appearance as original
  labs(x = "Var2") +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

plot

Z.Lin
  • 28,055
  • 6
  • 54
  • 94