Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to align bar plot labels to the left and right of a horizontal bar plot in ggplot2?

I have a horizontal bar plot and would like to align my bar labels to the left and right of each bar like shown below:
enter image description here

ie. I want the labels left aligned if the bar plot has a positive value and right aligned if the bar plot has a negative value.

Use the code below as a workable example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

value <- c(3,2,1,-1,-2,-3)
label <- factor(c("Arnold","Bob","Chris","David","Emma","Frank"))

df <- data.frame(value, label)

ggplot(df, aes(x = reorder(label, value), y = value)) +
    geom_bar(stat = "identity") +
    geom_text(aes(y = 0, label = label)) +
    coord_flip() +
    labs(x = NULL, y = NULL) +
    theme_classic() +
    theme(axis.ticks.y = element_blank(),
        axis.line.y = element_blank(),
        axis.text.y = element_blank())

Thank you

>Solution :

You can add an hjust aesthetic to geom_text, like this…

ggplot(df, aes(x = reorder(label, value), y = value)) +
  geom_bar(stat = "identity") +
  geom_text(aes(y = 0, label = label, hjust = 0.5 + 0.5 * sign(value))) +
  coord_flip() +
  labs(x = NULL, y = NULL) +
  theme_classic() +
  theme(axis.ticks.y = element_blank(),
        axis.line.y = element_blank(),
        axis.text.y = element_blank())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading