'How to make a spaghetti plot in ggplot R for categorical variables, and colour each line by ID?
I'm trying to make a spaghetti plot for some time series data and am having some trouble - my attempts so far do not show a separate line for each individual.
Individuals were sampled twice (in July and October) and at each time point I tested whether or not they were infected with nematodes (Yes/No).
I want to make a graph with "Nematode infection status" on the Y axis and "Month" (or "Time" if I have to make it numeric?) on the X axis.
My data looks like this:
ID Month Time nematode_infected
1 July 1 Yes
1 Oct 2 Yes
2 July 1 Yes
2 Oct 2 No
3 July 1 No
3 Oct 2 Yes
ID, Month, and nematode_infected are all factors
And my current code to graph it looks like this:
ggplot(recaptures_combined_long, aes(x=Time, y=nematode_infected, group=ID))+
facet_wrap(~RELATIVEAGE)+
labs(x="Month", y="Nematode infected?") + geom_line()
This is what I get (note that I have ~70 different IDs so there should be 70 lines on this graph, but there are only 4 per graph)
If I use "colour = ID" instead of "group = ID", I get this mess.
What I want is something like this, but with each line (each ID) a different colour:
Any idea how I could go about producing this graph? Thank you!
Edit - the solution was:
ggplot(recaptures_combined_long, aes(nematode_infected, Month, color = as.factor(ID), group = ID) )+
facet_wrap(~RELATIVEAGE)+ labs(x="Nematode infected?", y="Month")+
geom_line(position=position_dodge(width=0.2))+theme_classic() +
coord_flip() + theme(legend.position="none")
Solution 1:[1]
Is this what you are looking for?
df <- read.table(text =
"ID Month Time nematode_infected
1 July 1 Yes
1 Oct 2 Yes
2 July 1 Yes
2 Oct 2 No
3 July 1 No
3 Oct 2 Yes",
h = T)
library(ggplot2)
ggplot(df) +
geom_line(aes(Month, nematode_infected, color = as.factor(ID), group = ID))

Created on 2022-02-11 by the reprex package (v2.0.0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nniloc |
