ggplot2中基于`..count..`变量的{geom_label`的y值

时间:2018-08-26 02:54:50

标签: r ggplot2 label histogram tidyverse

我想创建一个直方图,其中有一条垂直线表示平均值,并在该线上附加了一个标签,以给出平均值的准确值。

我可以轻松地创建一条带有垂直线的基本直方图。

# needed library
library(ggplot2)

# mean to be used later
x_mean <- mean(x = iris$Sepal.Length, na.rm = TRUE)

# creating basic plot with line for mean
(
  plot <- ggplot(data = iris,
                 mapping = aes(x = Sepal.Length)) +
    stat_bin(
      col = "black",
      alpha = 0.7,
      na.rm = TRUE,
      mapping = aes(y = ..count..,
                    fill = ..count..)
    )  +
    geom_vline(
      xintercept = x_mean,
      linetype = "dashed",
      color = "red",
      na.rm = TRUE
    ) +
    scale_fill_gradient(name = "count",
                        low = "white",
                        high = "white") +
    guides(fill = FALSE)
)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

现在我可以使用以下代码在此行添加标签:

# adding label to the line
plot +
  geom_label(mapping = aes(
    label = list(bquote("mean" == ~ .(
      format(round(x_mean, 2), nsmall = 2)
    ))),
    x = x_mean,
    y = 5  # how to automate this value choice?
  ),
  parse = TRUE)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

现在,这里的问题是我正在对ygeom_label)的y = 5值进行硬编码。这不是理想的,因为如果我更改数据或变量或二进制宽度,y = 5将不再是y轴的中间位置。我尝试设置y = max(..count..)/2,但这会导致以下错误:

  

FUN(X [[i]],...)中的错误:找不到对象'count'

总结一下: 在这种情况下,如何自动选择y的{​​{1}}值,以使无论计数范围如何,标签始终位于Y轴的中心?

1 个答案:

答案 0 :(得分:5)

通过用@GetMapping public String getSumOfWord(@RequestParam @Size(min= 1, max = 3 , message = "word must be less than 3 characters") String word){ } 替换代码中的硬编码plot,可以从y = 5获取当前y轴范围。

这样,如果参数发生变化,则说明比例发生了变化。

y = mean(layer_scales(plot)$y$range$range)