I have the following problem: I want to add labels to my points in a scatterplot created with ggplot2 and ggplotly. I have read several posts here how to do that with geom_text()
. However, I always get a NULL
return if I want to print my plot. Unfortunately, I cannot post my exact data as it is confidential. However, my data frame in which all values to plot are stored in is generally structured in the following way: I have a xvar
column with characters which represents my x-variable. I have a numeric column yvar
for the y-axis. Then I have a column category
which I use to group the data and get similar colours for my points in the plot. And I have a column pLabel
which contains numeric values which I want to use as labels in the plot.
I coded it in the following way (given the described data frame df
):
pl1 <- ggplotly(ggplot(df,aes(x=xvar,y=yvar,text = paste("sqrt(z):", df$pLabel))) + geom_point(aes(colour=df$category)))
pl1 <- pl1 + geom_text(aes(label = df$pLabel), hjust = -0.05,vjust = 0.05)
print(pl1)
If I just print pl1 using only the first line of code, it plots everything without the labels. However, it returns NULL
if I run all three lines of code. How do I need to adjust this that I get my plot and not just a NULL
return in the console? Thanks!