沿离散比例调整几何位置

ren*_*nsa 3 r ggplot2

我试图将文本注释放置在具有小平面和离散轴的图上。我可以使用 将注释的位置与点联系起来aes(),但我想稍微移动它们以保持点的可读性。如果微移是在数字范围内,那就没问题:

data <- data.frame(
    category = c("blue", "yellow", "red", "green"),
    rating = 1:4)

gp <- ggplot(data) + geom_point(aes(x = category, y = rating)) +
    geom_text(aes(label = "I have a label!", x = category, y = rating + 0.5))
Run Code Online (Sandbox Code Playgroud)

但如果我尝试以非数字比例(在本例中为字符)执行此操作,则会失败:

gp <- ggplot(data) + geom_point(aes(x = category, y = rating)) +
    geom_text(aes(label = "I have a label!", x = category + 0.5, y = rating))
gp

Error in unit(x, default.units) : 'x' and 'units' must have length > 0
In addition: Warning messages:
1: In Ops.factor(category, 0.5) : + not meaningful for factors
2: Removed 4 rows containing missing values (geom_text).
Run Code Online (Sandbox Code Playgroud)

我可以使用hjustvjust稍微移动它们,但由于它们旨在对齐文本而不是定位文本,因此即使在最大程度上,它们也没有真正将注释移得足够远。有没有办法确定离散变量映射到的数字比例,或者有另一种方法来手动调整 的geom_text位置?

ddi*_*iez 5

您可以使用 hjust (或 vjust)来定位文本:

ggplot(data) + geom_point(aes(x = category, y = rating)) + 
    geom_text(aes(label = "I have a label!", x = category, y = rating), hjust=-.1)
Run Code Online (Sandbox Code Playgroud)