bjorn2bewild
bjorn2bewild

Reputation: 1019

Conditionally assign geom_text placement for bar charts with ggplot2

I am having an issue when making bar charts with mixed sign values in ggplot2. Take the following example:

df <- data.frame(year = letters[1:2],
                 value = c(1, -1))

ggplot(df, aes(year, value)) +
  geom_col() +
  geom_text(aes(label = value), vjust = 0.0, size = 5)

Which yields:

enter image description here

I would like to be consistent with the placement of the text - either below or on top of the bars. This is tricky because in both cases in the graph above, the text is directly above the value. However, because the first value is positive and the second value is negative the text appears in a different location relative to the bar. What I would like to see is (adjustments in red):

enter image description here

My question is: Is it possible to conditionally format label placement based on the sign of the value?

Upvotes: 3

Views: 463

Answers (1)

Yifu Yan
Yifu Yan

Reputation: 6116

df <- data.frame(year = letters[1:3],
                 value = c(1, -1,-5)) %>%
    mutate(text_location = ifelse(value < 0,0,value))

ggplot(df, aes(year, value)) +
    geom_col() +
    geom_text(aes(y = text_location,label = value), vjust = 0.0, size = 5)

enter image description here

Upvotes: 1

Related Questions