How to vertically or horizontally adjust label for only some bars in ggplot2 geom_col

90 views Asked by At

I have created a graph (run code below) and I would like to adjust the position (using hjust) for only two of the bars ("Difficult" and "Very Difficult") so that their labels appear outside (to the right) of the bars.

Is there a way to only adjust the horizontal position of the label in only a few columns in gggplot?

I know there is the option to expand my x axis (y because it's flipped) and include all labels outside of the bars using hjust but I the approach above is preferable as uses less space when printed for documents.

library(ggplot2)
library(RColorBrewer)
library(forcats)

survey_understanding <- data.frame("Survey_difficulty"   = c("Very simple", "Simple", "OK", "Confusing at times", "Difficult", "Very difficult"),
                             "n"        = c(384, 274, 142, 57, 7, 6),
                             "Percent"  = c("44%","31%", "15%", "7%", "1%", "1%"))

survey_understanding_graph <- ggplot(survey_understanding, aes(x = fct_reorder(Survey_difficulty, n), Survey_difficulty, y = n, fill = Survey_difficulty)) +
  geom_col() +
  coord_flip()+
  geom_text(aes(label = with(survey_understanding, paste(n, paste0('(', Percent, ')')))), hjust = 1.1, colour = "black", size = 3) +
  ylab("n") +
  xlab("Survey difficulty") +
  theme_light() +
  theme(legend.position = "none") +
  scale_fill_brewer(palette="Set1")

survey_understanding_graph

Answers to both options would be great.

1

There are 1 answers

2
stefan On

You could move hjust inside aes(), then use an ifelse to set the value:

library(ggplot2)
library(forcats)

ggplot(
  survey_understanding,
  aes(
    y = fct_reorder(Survey_difficulty, n),
    x = n,
    fill = Survey_difficulty
  )
) +
  geom_col() +
  geom_text(
    aes(
      label = paste0(n, " (", Percent, ")"),
      hjust = ifelse(n > 50, 1.1, -.1)
    ),
    colour = "black", size = 3
  ) +
  labs(x = "n", y = "Survey difficulty") +
  theme_light() +
  theme(legend.position = "none") +
  scale_fill_brewer(palette = "Set1")

enter image description here