0

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!

DolemiteMofo
  • 39
  • 1
  • 6
  • 2
    I think the easier way to do is would be using grid.arrange instead of faceting. `p1 <- ggplot(subset(df2, variable==c(colA,colB))) + geom_line(aes(x=x,y=value, color=variable)) ` and `p2 <- ggplot(subset(df2, variable==c(colC)) + geom_line(aes(x=x,y=value,color=variable))`. After that `library(gridExtra)` and `grid.arrange(p1,p2)`. – Jd Baba Feb 24 '14 at 17:29
  • I am still having some difficulty getting this to work... perhaps it is because I am including the index in the original data frame? say I was to do df <- data.frame(colA, colB, colC) How would I melt df2 to be in a useable form to use ur solution? – DolemiteMofo Feb 24 '14 at 17:47
  • I split the data into 2 different data frames and used grid.arrange to stitch them together and it worked, but I would still appreciate a more elegant solution. – DolemiteMofo Feb 24 '14 at 17:54
  • Can you include `dput(df)` so that I could post an example. – Jd Baba Feb 24 '14 at 18:23

1 Answers1

1

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")
BrodieG
  • 51,669
  • 9
  • 93
  • 146