0
votes

I would like to plot multiple lines in a single ggplot, where each line would represent relationship between x and y given two or more parameters.

I know how to do that for one parameter:

Take following example data:

library(ggplot2)
library(reshape2)

rs = data.frame(seq(200, 1000, by=200), 
                runif(5), 
                runif(5), 
                rbinom(n = 5, size = 1, prob = 0.5)) 
names(rs) = c("x_", "var1", "var2", "par")

melted = melt(rs, id.vars="x_")

ggplot(data = melted, 
       aes(x = x_, y = value, group = variable, col = variable)) + 
  geom_point() + 
  geom_line(linetype = "dashed")

This plots three lines one for var1, one for var2 and one for par.

current

However, I would like four lines: one for var1 given par=0 and another one for var1 given par=1, and the same then again for var2.

How would this scale up, for example if I want that the condition is a combination of multiple parameters (e.g. par2 + par)?

2

2 Answers

2
votes

You need to adjust your melt function and add a group column which has both par and var details. I think below is what you want?

library(reshape)
library(ggplot2)
rs = data.frame(seq(200, 1000, by=200), runif(5), runif(5), rbinom(n = 5, size = 1, prob = 0.5))
names(rs)=c("x_", "var1", "var2", "par")

melted = melt(rs, id.vars=c("x_", "par"))
melted$group <- paste(melted$par, melted$variable)

ggplot(data=melted, aes(x=x_, y=value, group =group, col=group))+ geom_point() + geom_line(linetype = "dashed")
3
votes

If you melt the data in a different way, you can use par to change the shape and linetype of your lines, so it's nice and clear which line is which:

rs_melt = melt(rs, id.vars = c("x_", "par"))

ggplot(rs_melt, aes(x = x_, y = value, colour = variable, 
                    shape = factor(par), linetype = factor(par))) +
    geom_line(size = 1.1) +
    geom_point(size = 3) +
    labs(shape = "par", linetype = "par")

Output:

enter image description here