Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

r - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
  )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...