0
votes

In R, I would like multiple individual density plots, preferably using the ggplot2 package. The data frame has variable V1, which has multiple levels (ie see data example below).

V1 V2
1  5
1  4 
1  2
2  3
2  8
2  6
3  5
3  9

How could I use qplot or ggplot to create density plots for V1=1 V1=2 and V1=3, in which V2 values are tied to the values of V1 (ie the density plot for V1=1 only accounts for V2=(5, 4, 2))?

1

1 Answers

0
votes

Try

ggplot(df1, aes(x=V2)) +
             geom_density(aes(group=V1, colour=V1, fill=V1))+
             theme_bw()

Update

You could use facet_wrap to create individual plot

 ggplot(df1, aes(x=V2))+
              geom_density(aes(colour=V1, fill=V1))+
              facet_wrap(~V1)+
              theme_bw()

data

df1 <- structure(list(V1 = c(1, 1, 1, 2, 2, 2, 3, 3, 3), V2 = c(5, 4, 
 2, 3, 8, 6, 5, 9, 10)), .Names = c("V1", "V2"), row.names = c(NA, 
9L), class = "data.frame")