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

label position in stat_bin for geom_histogram: how to adress ..count.. in the position_nudge method?

提问人:nadja 提问时间:8/10/2023 最后编辑:dandrewsnadja 更新时间:8/10/2023 访问量:32

问:

我有input_values作为小题大做:input_values

对于这些 alues,我想绘制一个直方图,其中列被标记(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..))

[this is the result (plus a bit styling)](https://i.stack.imgur.com/bvjDu.png)

标签总是位置太高。我估计类似“stat_bin(..., position = position_nudge(y = ..计数。。*-0.1)) 可以解决问题。但是我不能以这种方式处理我的计数值,对于它似乎有效的 x,请参阅此处

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

r 标签 统计 几何直方图

评论

0赞 nadja 8/10/2023
对不起图像,我无法让代码块工作(也没有)值 [1,] 0.1939713 [2,] 0.2042603 [3,] 0.2191685 [4,] 0.2346884 ...代码 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=..计数..))
1赞 dandrews 8/10/2023
只需复制您的代码并使用 ''' 开始。还要提供一些数据。使用并粘贴分配给对象的结果dput(input)

答:

2赞 stefan 8/10/2023 #1

问题是您设置了 .旋转标签时,设置的标签与条形图顶部对齐,然后用于移动它们。另请注意,我使用符号代替符号,因为后者在 中已弃用。hjust=-1hjust=0position = 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`.