0

I am trying to add labels in line graph but am unable to do so. I want to add lable such that blue line mentiones 'model_1'; red line mentioned 'model_2' and darkgreen line mentioned 'model_3'

Attaching the code below

p1 <- ggplot(data = Auto, aes(x = horsepower, y = mpg)) +
  geom_point() +
  geom_line(aes(y = fitted(lm_mpg_1)), color = "blue", size = 1) +
  geom_line(aes(y = fitted(lm_mpg_2)), color = "red", size = 1) +
  geom_line(aes(y = fitted(lm_mpg_3)), color = "darkgreen", size = 1)

I have tried to use geom_text, geom_label and annotate function however they give me error.

The code I tried was:

p1 + geom_text(label = c('model_1','model_2','model_3'))
stefan
  • 90,330
  • 6
  • 25
  • 51
Sonick
  • 11
  • 2
  • Welcome to SO! It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. Otherwise we can't run your code and in most cases it#s hard to come up with a working solution. Also, it would be helpful if you include the error message you get when running your code. – stefan Nov 07 '22 at 16:30
  • Greetings! Usually it is helpful to provide a minimally reproducible dataset for questions here so people can troubleshoot your problems. One way of doing this is by using the `dput` function. You can find out how to use it here: https://youtu.be/3EID3P1oisg – Shawn Hemelstrand Nov 15 '22 at 03:45

1 Answers1

0

You don't have any data. You can use dput to share your data. In the meanwhile I have used mtcars as an example below:

# library
library(ggplot2)
 
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
 
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_text(
    label=rownames(data), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_label(
    label=rownames(data), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 4, y = 25, label = "Some text")
Shubham
  • 220
  • 2
  • 10