如何使用ggrepel放置数据标签

问题描述

首先是样本数据和一些操作

  A<- c(150,125,-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. 在条形和标签之间添加一些空间
A <- c(150,125,-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,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)
  )

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...