Home > OS >  Mark and label one point in R scatterplot
Mark and label one point in R scatterplot

Time:11-11

I have created a scatterplot in R. Now I need to mark one point in that scatterplot, label it and add a legend to that.

I have tried below code. Although it does not give any error, it does not do anything to the scatterplot.

plot(revenue~price,data=df,pch=20)
legend(x="topright",legend = df1$city,lty = 1,cex=0.4)
text(df$revenue[36.9257], df$price[14.7287],"Lowest",cex=10, font=3,col="green")

CodePudding user response:

#create dataset
df <- data.frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(7, 9, 14, 19, 12, 15),
                 z=c('a', 'b', 'c', 'd', 'e', 'f'))

#create scatterplot 
plot(df$x, df$y)

#add the filled point
points(df$x[5], df$y[5], pch=16, col = "red")

#add a label to the fifth point of the dataset
text(df$x[5], df$y[5]-1, labels=df$z[5], col = 'red')

text() function:

  • the first argument is a point of the x-axis,
  • the second of y, here we give -1 to coordinate because we want that the label to not overlap with the point itself
  • the third argument is the label, which you declare of z vector of the same point.

the result of the code

  • Related