I am trying to find a way to wrap geom_text/geom_label on a scatterplot (ggplot). I have seen ways this can be done manually inputting the co-ordinates - but i will have 10-20 variables, so this will not be possible.
I have a data frame that looks like this...
df <- data.frame(x =c(2,4,6,8),
y =c(7,3,5,4),
label =c("this variable has a long name which needs to be shortened",
"this variable has an even longer name that really needs to be shortened",
"this variables has a name that is much longer than two of the other name, so really needs to be shortened",
"this is pretty long too"))
and i want to make the following plot (but with wrapped labels)
ggplot(df, aes(x=x, y=y, label=label))+
geom_point()+
geom_text(nudge_y=0.05)+
xlim(0,10)+
theme_minimal()+
ggtitle("title")
This is the plot:
Have you tried str_wrap
? You might need to play around with width
argument and nudge_y
according to your actual data.
library(ggplot2)
df$label <- stringr::str_wrap(df$label, 25)
ggplot(df, aes(x=x, y=y, label=label))+
geom_point()+
geom_text(nudge_y=0.5)+
xlim(0,10)+
theme_minimal()+
ggtitle("title")