【发布时间】:2021-08-03 09:47:39
【问题描述】:
我正在绘制 2 个密度并尝试添加一些注释,这些注释在文本旋转 90 度时水平对齐,但当注释的字符长度不同时,我似乎无法让它们对齐。
library(ggplot2)
n <- 10000
mu_a <- .089
mu_b <- .099
s_a <- .0092
s_b <- .004
df <- data.frame(
variant = factor(c(rep("A", n),rep("B", n))),
p = c(rnorm(n = n, mean = mu_a, sd = s_a), rnorm(n = n, mean = mu_b, sd = s_b)))
ggplot(df, aes(x = p, fill = variant)) +
geom_density() +
scale_x_continuous(labels = scales::percent) +
scale_y_continuous(expand = expansion(mult = c(0, .1))) +
annotate("text",
x = c(mu_a,mu_b),
y = Inf,
vjust = "center",
hjust = 6,
label = c("5char","06char"),
angle = 90
)
由reprex package (v0.3.0) 于 2021-05-12 创建
在https://i.imgur.com/CxW1pjP.png处绘制图像
我尝试使用 scale_y_continuous(y = ..scaled..) 将 y 轴更改为 0:1 比例,然后将注释 y 值设置为固定位置,例如 y = 0.2,但密度大小不合适。尝试了各种 hjust 和 vjust 的组合。我认为这些应该像情节的百分比一样起作用。所以vjust = 0.2 意味着情节增加了 20%,但对我来说并不是这样。我没想到通过将文本旋转 90 度,hjust 和 vjust 会交换,但这似乎是发生的事情。
【问题讨论】:
-
使用stackoverflow.com/questions/7705345/… 找到的灵感,我尝试从图中获取 y 比例限制,并设置相对于该值的注释 y 值。因此,如果绘图对象是
g,这将获取比例上限label_y <- ggplot_build(g)$layout$panel_scales_y[[1]]$range$range[[2]] * 0.2。似乎可以始终将标签放置在绘图高度的 20% 处。构建绘图后添加注释之外的更好方法?
标签: r ggplot2 density-plot