user9629272
user9629272

Reputation:

How to add multiple layers from one dataframe in ggplot?

Sorry if this is a stupid question, I am still new at R.

I am struggling with adding multiple layers from two different columns of a dataframe. This is my script:

b <- rnorm(500, mean=300, sd=60)
c <- rnorm(500, mean=350, sd=15)
id <- rep(1:50, each=10)
visit <- rep(1:10, 50)
df <- data.frame(id, visit, b, c)

I want to create a graph with visit on the x-axis, and b and c in the y-axis.

ggplot(df, aes(x=visit, y=b)) + 
  geom_jitter(color="blue") + 
  geom_jitter(y=c, color="red")

This doesn't work, however. I know this does work when I have two different dataframes and the same column name. Is this the only way for me to add both b and c to the graph? Or is there another way?

Upvotes: 3

Views: 611

Answers (2)

divibisan
divibisan

Reputation: 12155

The correct way to add multiple layers from one dataplot is to specify the aes in each layer:

ggplot(df) + 
  geom_jitter(aes(x=visit, y=b), color="blue") + 
  geom_jitter(aes(x=visit, y=c), color="red")

enter image description here

For your specific example, the most tidy way to do this is to do what @GGamba suggests and make a tidy dataframe that has color as a categorical variable.

Upvotes: 2

GGamba
GGamba

Reputation: 13680

If you only have a couple of group you can override the aes in each geom:

library(ggplot2)

ggplot(df,aes(x=visit,y=b)) + 
  geom_jitter(color="blue") + 
  geom_jitter(aes(y=c), color="red")

But if you need to generalize, the approach is to have a 'tidy' dataframe:

library(tidyr)
df %>% 
  gather(key, value, -id, -visit) %>% 
  ggplot() +
  geom_jitter(aes(visit, value, color = key))

Data:

b <- rnorm(500,mean=300,sd=60)
c <- rnorm(500,mean=350,sd=15)
id <- rep(1:50,each=10)
visit <- rep(1:10,50)
df <- data.frame(id,visit,b,c)

Created on 2018-05-15 by the reprex package (v0.2.0).

Upvotes: 1

Related Questions