gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:47:49 25 4
gpt4 key购买 nike

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

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

# 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`.

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

Error in FUN(X[[i]], ...) : object 'count' not found

总结一下:如何选择y值为 geom_label在这种情况下是否可以自动化,以便无论计数范围如何,标签始终以 Y 轴中间为中心?

最佳答案

您可以通过将代码中的硬编码 y = 5 替换为 y = Mean(layer_scales) 来从 plot 获取当前 y 轴范围(图)$y$range$range)

这样,如果参数发生变化,则会考虑比例的变化。

# layer_scales(plot) gives the scale information for plot
> layer_scales(plot)$y
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
<ScaleContinuousPosition>
Range: 0 -- 12
Limits: 0 -- 12

# this is the actual vector for y-axis scale range
> layer_scales(plot)$y$range$range
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[1] 0 12

# this is the y-axis midpoint value
> mean(layer_scales(plot)$y$range$range)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
[1] 6

关于r - ggplot2 中 `geom_label` 的 y 值基于 `..count..` 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52022833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com