Reputation: 1460
I have one following example data:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
Normally we plot the two variable VC
and OJ
in the same plot like this:
ggplot(data=df2, aes(x=dose, y=len, group=supp, colour=supp)) +
geom_line()
What I would like to get is to plot VC
in a reversed Y axis while still keeping the two variables in the same plot and share the same x axis. It should be like the pic below:
How can I do it with ggplot2? Thanks a lot.
Upvotes: 0
Views: 1180
Reputation: 24139
I'm not sure if this is what you are looking for.
ggplot2, does not handle the secondary axis very easily. In order to reverse plot this variable, needed to multiple by -1 to reverse it.
library(tidyr)
#widen the dataframe, to separate the variables into different columns
df3<-pivot_wider(df2, id_cols = dose, names_from = supp, values_from = len)
ggplot(data=df3) +
geom_line(aes(x=dose, y=OJ, group="OJ", color="OJ")) +
geom_line(aes(x=dose, y=-1*VC, group="VC", color="VC"))
Upvotes: 1
Reputation: 16178
You can multiply values of len for supp == VC by -1 and then plot as usual.
Then, set new breaks and labels using scale_y_continuous
.
library(dplyr)
library(ggplot2)
df2 %>%
mutate(len = ifelse(supp == "VC", len*-1,len)) %>%
ggplot(aes(x = dose, y = len, color = supp, group = supp))+
geom_point()+
geom_line()+
scale_y_continuous(limits = c(-40,40), breaks = seq(-20,20, by = 20),
labels = c(20,0,20))
Is it what you are looking for ?
Upvotes: 1