geom_histogram stat_bin中的标签位置:如何在position_nudge方法中解决..count..?

问题描述 投票:0回答:1

我有 input_values 作为小标题: input_values

对于这些值,我想绘制一个直方图,其中标记了列(90°角,几乎直接在列顶部)。

as_tibble(input_values) %>% ggplot(aes(x = values) + geom_histogram(stat = "bin") + stat_bin(geom='text', angle = 90, family = "Calibri", hjust=-1, vjust=0.4, aes(label=..count..))

标签总是位置太高。我认为类似“stat_bin(...,position =position_nudge(y = ..count..*-0.1))”的东西可以解决问题。但是我无法以这种方式处理我的计数值,因为 x 似乎可以工作,请参阅此处

我还尝试了 stat = count、position =position_nudge(y = 1000) 等,但它不起作用,因为标签越往上,计数越高。

r label stat geom-histogram
1个回答
1
投票

问题是你设置了

hjust=-1
。当您旋转标签时,设置
hjust=0
将标签与条形顶部对齐,然后使用
position = position_nudge(...)
移动它们。另请注意,我使用
after_stat
而不是
..
表示法,因为后者在
ggplot2 >= 3.4.0
中已被弃用。

使用一些虚假的随机示例数据:

library(ggplot2)

set.seed(123)

input_values <- data.frame(
  values = rnorm(3e6)
)

ggplot(input_values, aes(x = values)) +
  geom_histogram(stat = "bin") +
  stat_bin(
    geom = "text", angle = 90, family = "Calibri",
    hjust = 0, position = position_nudge(y = 1000),
    aes(label = after_stat(count))
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

© www.soinside.com 2019 - 2024. All rights reserved.