I have the following problem: I want to create a plot using ggplot, showing the relationship between two variables (Microplastic quantification in mussels, denoted as MP and Lipofuscinaccumulation denoted as Lip) of different treatment groups and independence of exposure time.
My data look like this:
And here is my Code:
ggplot(Catrv_all,aes(Lip,MP,color=treatment))+
geom_smooth(method="lm", se=FALSE)+
geom_point(size = 2)+
theme(legend.position = "bottom")+
theme(plot.title = element_text(hjust = 0.5))+
labs(x = "Lipofuscin accumulation [% area]",
y = "Microplastic quantification [% area]",
title = "Lipofuscin accumulation vs. Microplastic quantification")
The plot looks like this:
I recognized that ggplot obviously did not order the values in the correct way for exposure Time because the values disagree (it starts for example not with the value for 0 h).
My question is: how can I tell ggplot to reorder the values for MP and Lip in the right order in terms of exposure Time? Should I create second x-axes? If yes, how can I do that in ggplot?
I saw a lot of discussions in SO, that this is difficult to create a second x/y axes in ggplot, but I don't know how I should visualize my data in another way.
Update for my question: I heed advice of sconfluentus and found a very interesting answer of Ben Bolker in the following post: How can I plot with 2 different y-axes?
I adapted the provided code:
## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)
## split data set for treatment groups
MP_Ko<-Catrv_all$MP[1:8]
exp<-Catrv_all$expTime[1:8]
Lip_Ko<-Catrv_all$Lip[1:8]
## Plot first set of data and draw its axis
plot(exp, MP_Ko, pch=16, axes=FALSE, xlab="", ylab="",
type="b",col="black", main="Microplastic quantification vs. Lipofuscin accumulation in Controls")
axis(2,col="black",las=1) ## las=1 makes horizontal labels
mtext("Microplastic quantification [% area]",side=2,line=2.5)
box()
## Allow a second plot on the same graph
par(new=TRUE)
## Plot the second plot and put axis scale on right
plot(exp,Lip_Ko, pch=15, xlab="", ylab="",
axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Lipofuscin accumulation [% area]",side=4,col="red",line=4)
axis(4, col="red",col.axis="red",las=1)
## Draw the time axis
axis(1,pretty(range(Catrv_all$expTime, 672)))
mtext("Time (Hours)",side=1,col="black",line=2.5)
## Add Legend
legend("topright",legend=c("Microplastic quantification","Lipofuscin accumulation"),
text.col=c("black","red"),pch=c(16,15),col=c("black","red"))
... and got the following plot: enter image description here
Time consuming, but this approach was very helpful.