0

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.

Bob_123
  • 19
  • 3

1 Answers1

0

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Thanks @stefan, could you explain what "moving hjust" inside aes does in terms of ggplot2 functioning? Thanks! – Bob_123 Aug 11 '23 at 12:00
  • 1
    `hjust` and `vjust` are aesthetics of `geom_text` just like x, y, color, ..., i.e. you could add a column to your data to specify the alignment and map this column on `hjust` as usual. – stefan Aug 11 '23 at 12:05