0

I have an issue on how to display segment with geom_segment in ggplot graph. I have individuals which are measurements on height and body mass related to Age, and after making a plot I would like to link those two variables (height and body mass) to see clearly one individual with adding its label (here there are identify by number, putted in character).

So its look like this :

ID height Bodymass Age
2154 1,80 80 42

And I made this plot :

enter image description here

And I would like something like this :

enter image description here

I have tried with geom_segment and geom line but still some errors which I don't understand Here what I have tried before :


ggplot(BM_height, aes(x=Age)) + 
  geom_smooth(aes(y=height), method="loess", col="blue") +
  geom_point(aes(y=height),col="blue")+
  geom_smooth(aes(y=BodyMass * scaleFactor), method="loess", col="red") +
  geom_point(aes(y=BodyMass/10),col="red")+
  #geom_segment(aes(x = Age, y = height, xend = Age, yend = BodyMass))+
  scale_y_continuous(name="height (cm)", sec.axis=sec_axis(~./scaleFactor, name="Body mass (g)")) +
  theme(
    axis.title.y.left=element_text(color="blue"),
    axis.text.y.left=element_text(color="blue"),
    axis.title.y.right=element_text(color="red"),
    axis.text.y.right=element_text(color="red")
  )
)
#geom_text(BM_height, mapping=aes(label=ID_new), stat="identity")
Kat
  • 15,669
  • 3
  • 18
  • 51
hohugu
  • 1
  • 1
  • Something in the line of `geom_line(aes(group = id))`. – mhovd Feb 28 '23 at 12:17
  • Unfortunately, I still have the same error message : Error in `geom_line()`: ! Problem while setting up geom. ℹ Error occurred in the 5th layer. Caused by error in `compute_geom_1()`: ! `geom_line()` requires the following missing aesthetics: y Run `rlang::last_error()` to see where the error occurred. – hohugu Feb 28 '23 at 12:45
  • 1
    If you provided a minimal, reproducible example, including sample data, it would be possible for us to help you. – mhovd Feb 28 '23 at 13:17
  • in `geom_segment`, `yend = BodyMass` should be `yend = BodyMass*scaleFactor`. There also seems to be a mistake in the second `geom_point` where the value 10 is hard-coded rather than using `scaleFactor`, so the red smooth doesn't go through the red points – Miff Feb 28 '23 at 13:32
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Feb 28 '23 at 14:43
  • Yes sorry, next time I will put a reproducible example ;) Thank you everyone for you help !! And Thanks also to Miff, you're right ! Indeed I had to put everywhere *scaleFactor with BodyMass and so the curve smooth, follow the red points so. Thanks also Kat for having editing the question, I have to learn about that :D – hohugu Feb 28 '23 at 15:08

0 Answers0