Tim Wilcox
Tim Wilcox

Reputation: 1331

How to use ggrepel to place data labels

First is the sample data and some manipulations

  A<- c(150,125,0,-300,-350,-370)
  Series<- 
  c("Construction","Manufacturing","Information","Health_Care","Education","Government")

  testdf <- data.frame(A,Series)

  jobgrowth<-ggplot(data=testdf, aes(y=A, x = reorder(Series,A))) + 
  geom_col(color="blue") + coord_flip() +
  labs(x = NULL) + ggtitle("Interesting Title") +
  theme(plot.title.position = "plot",
      plot.title = element_text(hjust = 0.5))+
      

From looking around, I am finding that ggrepel is a good package for this (https://ggrepel.slowkow.com/articles/examples.html). However, my attempts result in an error

   Error: geom_text_repel requires the following missing aesthetics: label

So my question is where would insert the labels text and then how to get the data labels to fit on the right when the value is positive and on the left when it is negative? Construction, for example, would have 150 to the right of the bar.

Upvotes: 0

Views: 741

Answers (1)

stefan
stefan

Reputation: 123903

You don't need ggrepel. ggrepel is an excellent choice if you have to deal with overlapping labels. However, in case of your bar chart I would suggest to go with default geom_text like so:

Using ifelse you can

  1. set hjust to right or left align your labels
  2. add some space between the bars and the labels
A <- c(150, 125, 0, -300, -350, -370)
Series <-
  c("Construction", "Manufacturing", "Information", "Health_Care", "Education", "Government")

testdf <- data.frame(A, Series)

library(ggplot2)

ggplot(data = testdf, aes(y = A, x = reorder(Series, A))) +
  geom_col(color = "blue") +
  coord_flip() +
  scale_y_continuous(expand = expansion(mult = 0.5)) +
  geom_text(aes(label = A, hjust = ifelse(A > 0, 0, 1), y = A + ifelse(A > 0, 10, -10))) +
  labs(x = NULL) +
  ggtitle("Interesting Title") +
  theme(
    plot.title.position = "plot",
    plot.title = element_text(hjust = 0.5)
  )

Upvotes: 2

Related Questions