Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plot single point on geom_line without a y-value in the data frame?

I am looking to add a single point to my ggplot geom_line at a specific x-value. The x-value where I want the point to fall does not have an associated y-value in the data frame; however, I want the point to fall on the line.

df <- mtcars
ggplot(df,aes(disp,wt)) +
  geom_line() +
  geom_point() +
  geom_point(aes(x=200),color="red")

Ideally, I will only have one red point at x=200 and the point will fall on the ggplot geom_line(). Any information on how to do this is greatly appreciated–thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use approx to find the y-value. And I’d recommend using annotate() instead of a geom_* function to add one-offs to a graph.

ggplot(df, aes(disp,wt)) +
  geom_line() +
  geom_point() +
  annotate(
    geom = "point", 
    x = 200, 
    y = approx(x = df$disp, y = df$wt, xout = 200)$y,
    color="red"
)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading