加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

geom_text如何根据需要在文本上定位文本?

发布时间:2020-12-14 21:19:49 所属栏目:资源 来源:网络整理
导读:我想调整条形图上的文字. 我试图调整hjust / vjust以显示我喜欢它但似乎它不能正常工作. ggplot(data) + geom_bar(aes(name,count,fill = week),stat='identity',position = 'dodge') + geom_text(aes(name,label=count),hjust=0.5,vjust=3,size=2,position
我想调整条形图上的文字.

我试图调整hjust / vjust以显示我喜欢它但似乎它不能正常工作.

ggplot(data) + 
        geom_bar(aes(name,count,fill = week),stat='identity',position = 'dodge') +
        geom_text(aes(name,label=count),hjust=0.5,vjust=3,size=2,position = position_dodge(width = 1)) + 
        coord_flip()

所以我希望数字位于每个条形图上,中间位于右边缘,因此它的可读性不会像最后一部分那样重叠.

解决方法

编辑:

让hjust / vjust更智能地运行的更简单的解决方案是将组审美添加到geom_text然后调整和调整.位置自动调整组.

1.垂直方向

ggplot(data) + 
  geom_bar(
    aes(x = name,y = count,fill = week,group = week),position = 'dodge'
  ) +
  geom_text(
    aes(x = name,label = count,position = position_dodge(width = 1),vjust = -0.5,size = 2
  ) + 
  theme_bw()

这给出了:

2.水平方向

ggplot(data) + 
  geom_bar(
    aes(x = name,hjust = -0.5,size = 2,inherit.aes = TRUE
  ) + 
  coord_flip() + 
  theme_bw()

这给出了:

这不一定是执行此操作的最常用方法,但您可以使用填充相关的hjust(或vjust,取决于方向)变量.我不完全清楚如何选择调整参数的值,目前它是基于看起来正确的.也许其他人可以建议一种更通用的方法来选择这个参数值.

1.垂直方向

library(dplyr)
library(ggplot2)

# generate some data
data = data_frame(
  week = as.factor(rep(c(1,2),times = 5)),name = as.factor(rep(LETTERS[1:5],times = 2)),count = rpois(n = 10,lambda = 20),hjust = if_else(week == 1,5,-5),vjust = if_else(week == 1,3.5,-3.5)
)

# Horizontal
ggplot(data) + 
  geom_bar(
    aes(x = name,vjust = vjust),inherit.aes = TRUE
  ) + 
  coord_flip() + 
  theme_bw()

这是看起来像:

2.水平方向

ggplot(data) + 
  geom_bar(
    aes(x = name,inherit.aes = TRUE
  ) + 
  coord_flip() + 
  theme_bw()

这是看起来像:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读