假設我在下面ggplot
library(ggplot2)
set.seed(1)
df = data.frame(x = rnorm(100, 0, 1), y1 = rnorm(100, 10, 1), y2 = rnorm(100, 50, 1))
ggplot(df)
geom_point(aes(x = x, y = y1))
geom_label(aes(x = mean(range(df$x)), y = 10), label = 'Plot with y', label.padding = unit(.7, 'lines'), fill = '#000000', color = '#ffffff', alpha = 0.2)

現在有了第二個變數y2,我在下面ggplot
ggplot(df)
geom_point(aes(x = x, y = y2))
geom_label(aes(x = mean(range(df$x)), y = 10), label = 'Plot with y', label.padding = unit(.7, 'lines'), fill = '#000000', color = '#ffffff', alpha = 0.2)

我想修復geom_label這兩個圖中的相對垂直位置100 pixels/points,無論y axis.
是否有任何選項可以geom_label執行相同的操作?
任何指標都會非常有幫助
uj5u.com熱心網友回復:
一種選擇是將標簽添加為 grobs,通過annotation_custom它允許使用繪圖區域的相對坐標定位標簽。為方便起見,我使用gridtext::richtext_grob創建標簽 grob。
library(ggplot2)
library(gridtext)
set.seed(1)
df = data.frame(x = rnorm(100, 0, 1), y1 = rnorm(100, 10, 1), y2 = rnorm(100, 50, 1))
label_grob <- gridtext::richtext_grob(
text = 'Plot with y',
x = unit(0.5, "npc"),
y = unit(1, "npc") - unit(100, "pt"),
padding = unit(.7, "lines"),
r = unit(0.15, "lines"),
gp = grid::gpar(col = '#ffffff'),
box_gp = grid::gpar(col = '#000000', fill = '#000000', size = 0.25)
)
ggplot(df)
geom_point(aes(x = x, y = y1))
annotation_custom(grob = label_grob)

ggplot(df)
geom_point(aes(x = x, y = y2))
annotation_custom(grob = label_grob)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462734.html
