gpt4 book ai didi

r - 在 geom_boxplot (ggplot2) 中找到框的 x 坐标

转载 作者:行者123 更新时间:2023-12-04 03:10:33 27 4
gpt4 key购买 nike

我想添加文本以指示箱线图中的中值和铰链(箱的左侧或右侧)。我正在为文本的水平定位而苦苦挣扎。如何计算框的 x 坐标(左和右)?(或者如何将它们适本地放置在框的左侧或右侧)。

set.seed(0)
d <- data.frame(x = rnorm(20))
pos <- quantile(d$x)[2:4]
s <- data.frame(pos, q=names(pos))

ggplot(d, aes("A", x)) +
geom_boxplot() +
geom_text(aes(y=pos, label=q), s, hjust=5)

enter image description here

最佳答案

对于箱线图,ggplot2 在 x=1 处绘制第一个箱线图,然后在 x=2、3、3 等处绘制下一个箱线图。如果每个因子水平只有一个图(即没有在这些点分割),条形的宽度为 0.75,每边 0.375。

因此,对于您的示例,您想要添加带有 x = (1 - 0.375) 的 geom_text,并留出一点空间以确保它不会重叠:

library(ggplot2)

set.seed(0)
d <- data.frame(x = rnorm(20))
pos <- quantile(d$x)[2:4]
s <- data.frame(pos, q=names(pos))

ggplot(d, aes("A", x)) +
geom_boxplot() +
geom_text(aes(y=pos, label=q), x=1-0.375,s)

enter image description here

如果你有多个箱线图,你想打电话:

geom_text(aes(y=pos, label=q, x = as.numeric(factor(var))-0.375), s)

关于r - 在 geom_boxplot (ggplot2) 中找到框的 x 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33738124/

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