Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_text overlapping with data points despite using nudge_x and nudge_y

Tags:

r

ggplot2

I'm trying to have text labels not overlap with the data points in a scatterplot made in ggplot2.

I've tried using the nudge_ arguments in geom_text():

library(ggplot2)

df <- data.frame(trt = c("a", "b", "c"),
                 resp = c(2, 3, 4))

ggplot(df, aes(resp, trt)) +
    geom_point() +
    geom_text(aes(label = resp , nudge_y = 2, nudge_x = 2))

However, as we can see, the text overlaps with the point: current output

Is there any way we can fix this? Also, what's the use of nudge_x and nudge_y? I don't quite get it from the manual.

like image 240
watchtower Avatar asked Oct 26 '25 14:10

watchtower


1 Answers

The issue was that nudge_x & nudge_y should be outside of aesthetics.

df <- data.frame(trt = c("a", "b", "c"), resp = c(2, 3, 4))

ggplot(df, aes(resp, trt)) +
       geom_point() +
       geom_text(aes(label = resp), nudge_y = -0.1)

This fixes the issue. I have reduced nudge_y values.

Here's the graph: Graph

like image 52
watchtower Avatar answered Oct 29 '25 04:10

watchtower