Gabriel
Gabriel

Reputation: 45

How to create a distance between the geom text and the bar

I have a following problem. I want increase a padding bettween the text and the bar. But at same time, the value of text must be in the box of ggplot2 device.

Reproducible examples:

diamonds %>% 
  group_by(color) %>% 
  count() %>%
    ggplot(aes(color, y = n)) + 
    geom_bar(stat = "identity") + 
      geom_text(
        aes(label = n), 
            vjust = 0.5, 
            hjust = "inward") +
  coord_flip()

Upvotes: 1

Views: 1075

Answers (1)

OTStats
OTStats

Reputation: 1868

Because you flipped coordinates it looks like your hjust and vjust calls were applied incorrectly. With this in mind, I only adjusted the text horizontally and I expanded the limits to fit the label for G, which would otherwise be cut off by the limits of the graph.

diamonds %>% 
    group_by(color) %>% 
    count() %>%
    ggplot(aes(color, y = n)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = n), 
    hjust = -.5) +
    coord_flip() + 
    expand_limits(y = 12000)

enter image description here

Or, if you want the text labels to be within the bars you can use the following.

diamonds %>% 
    group_by(color) %>% 
    count() %>%
    ggplot(aes(color, y = n)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = n), 
    hjust = 1.5) +
    coord_flip()

enter image description here

Upvotes: 2

Related Questions