首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ggrepel放置数据标签

如何使用ggrepel放置数据标签
EN

Stack Overflow用户
提问于 2021-01-05 20:10:22
回答 1查看 310关注 0票数 0

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

代码语言:javascript
复制
  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)。但是,我的尝试会导致一个错误。

代码语言:javascript
复制
   Error: geom_text_repel requires the following missing aesthetics: label

那么,我的问题是,在哪里插入标签文本,然后如何使数据标签在值为正时在右边,当值为负值时,在左边?例如,建筑将有150人在酒吧的右边。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-05 20:24:00

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

使用ifelse你可以

  1. hjust设置为右或左对齐标签
  2. ,在栏和标签

之间添加一些空格。

代码语言:javascript
复制
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)
  )

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65585887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档