问题描述
首先是样本数据和一些操作
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
你可以
- 将
hjust
设置为右对齐或左对齐您的标签 - 在条形和标签之间添加一些空间
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)
)