position_dodge in geom_text seemingly not working

Hi folks! I am trying to overlay some labels over dodged points but geom_text() does not appear to be respecting the position = position_dodge(width = 1) I'm providing.

Am I just missing something or this is a bug and I should file an issue on GitHub? Wanted to check first that it's not a user error :slight_smile:

reprex_data <- tibble::tribble(
    ~y, ~x, ~z,
    1, "a", "1",
    2, "a", "2",
    3, "b", "1",
    4, "b", "2"
)

ggplot(reprex_data, aes(x = x)) +
    geom_pointrange(
        aes(y = y, ymin = y - 1, ymax = y + 1, color = z),
        position = position_dodge(width = 1)
    ) +
    geom_text(
        aes(y = y, label = z),
        position = position_dodge(width = 1),
        color = "black"
    ) +
    theme_minimal()

Output:

plot

Desired, with the "z" labels on top of the points:

plot2

Your mapping of geom_text does not contain any variable against which to dodge; the x position is simply determined by the x column of the data. Here is an ugly example of having the text follow the dodged points because the color of the text depends on z.

ggplot(reprex_data, aes(x = x)) +
  geom_pointrange(
    aes(y = y, ymin = y - 1, ymax = y + 1, color = z),
    position = position_dodge(width = 1)
  ) +
  geom_text(
    aes(y = y, label = z, color = z), hjust = 1,
    position = position_dodge(width = 1)
  ) +
  theme_minimal()
1 Like

@FJCC is correct but I would use the group aesthetic:


ggplot(reprex_data, aes(x = x)) +
  geom_pointrange(
    aes(y = y, ymin = y - 1, ymax = y + 1, color = z),
    position = position_dodge(width = 1)
  ) +
  geom_text(
    aes(y = y, label = z, group = z),
    position = position_dodge(width = 1),
    color = "black"
  ) +
  theme_minimal()
2 Likes

Thank you @FJCC and @karawoo! The reason makes total sense.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.