given a dataframe of 3 columns, plot the first 2 on 1 axis, and the 3rd on a separate axis below it using ggplot2

StackOverflow https://stackoverflow.com/questions/21994595

  •  16-10-2022
  •  | 
  •  

Question

I have a dataframe with 4 columns: "x" "colA" "colB" "colC"

df <- data.frame(x, colA, colB, colC)
df2 <- melt(data=df, id.vars="x")

currently I am doing the following

ggplot(df2, aes(x=x, y=value, colour=variable)) + geom_line() + 
    facet_wrap( ~ variable, ncol=1, scales="free")

This plots the 3 series (colA, colB, colC) on 3 seperate axis

I want to plot colA and colB on 1 axis, and have a seperate axis under it containing only colC

Any idea how to accomplish this? Thanks!

Was it helpful?

Solution

Try:

df2$is.colC <- df2$variable == "colC"
ggplot(df2, aes(x=x, y=value, colour=variable)) + geom_line() + 
  facet_wrap( ~ is.colC, ncol=1, scales="free")

We just add a new variable that highlights whether the row is a "colC" row, and facet on that.

enter image description here

And the data for reference:

set.seed(1)
x <- 1:10
colA <- runif(10)
colC <- runif(10)
colB <- runif(10)
df <- data.frame(x, colA, colB, colC)
df2 <- melt(data=df, id.vars="x")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top