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

How do I connect geom_points for ID when col is not ID in ggplot?

I’m trying to make a ggplot (in Shiny): I have concentration-time data that I want to visualize. There’s an option for the user to colour different groups in the plot, for example, Species, Antibodies, etc. However, I also want them to see the different concentration-time graphs for every ID, so what I actually want to achieve is that the data is colored by Species but the data points for each individual are connected.

I can give you an example data set:

dfc <- data.frame(
  ID = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4),
  Conc = c(4, 3.5, 3, 1, 5, 4.5, 4, 2, 3, 2.5, 2, 1, 6, 5.5, 5, 4),
  Time = c(0.15, 1, 2, 3, 0.15, 1, 2, 3, 0.15, 1, 2, 3, 0.15, 1, 2, 3),
  Species= c("Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Mouse", "Mouse","Mouse","Mouse","Mouse","Mouse","Mouse","Mouse"))

I’m working on a Shiny app that is very big right now, so I won’t bother you with all code, but that’s just something easy right now. What I tried is this:

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

plot <- ggplot() + geom_point(dfc, mapping=aes(Time, Conc, col = Species)) + geom_line(dfc, mapping=aes("ID"))
plot

Obviously, this doesn’t work and I’m also not sure how to do this. I hope someone can help me with this because I feel like the answer is simple, but I can’t figure it out right now.

>Solution :

You could connect your points using group in your geom_line by ID like this:

library(ggplot2)
plot <- ggplot() + 
  geom_line(dfc, mapping=aes(x = Time, y = Conc, group = ID)) +
  geom_point(dfc, mapping=aes(Time, Conc, col = Species)) 
plot

Created on 2023-02-01 with reprex v2.0.2

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