Wang
Wang

Reputation: 1460

ggplot2 plots the two variables in the same plot but one variable with reversed y axis

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()

enter image description here

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:

enter image description here

How can I do it with ggplot2? Thanks a lot.

Upvotes: 0

Views: 1180

Answers (2)

Dave2e
Dave2e

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")) 

enter image description here

Upvotes: 1

dc37
dc37

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))

enter image description here

Is it what you are looking for ?

Upvotes: 1

Related Questions