如何使用ggrepel放置数据标签

How to use ggrepel to place data labels

首先是示例数据和一些操作

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

环顾四周,我发现 ggrepel 是一个很好的软件包 (https://ggrepel.slowkow.com/articles/examples.html)。但是,我的尝试导致错误

   Error: geom_text_repel requires the following missing aesthetics: label

所以我的问题是在哪里插入标签文本,然后如何让数据标签在值为正时位于右侧,在值为负时位于左侧?例如,建筑将在栏的右侧显示 150。

您不需要 ggrepel。如果您必须处理重叠标签,ggrepel 是一个很好的选择。但是,对于您的条形图,我建议使用默认值 geom_text,如下所示:

使用ifelse你可以

  1. hjust 设置为右对齐或左对齐标签
  2. 在条形和标签之间添加一些 space
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)
  )