Line charts by group

2019-06-05 14:01发布

问题:

I have the following data and I want to create a line chart conditional on group1 and group2 variable.

dat <- structure(list(group1 = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L),
                                         .Label = c("a", "b"),
                                         class = "factor"),
                      group2 = c(1L, 2L, 3L, 4L, 1L, 2L, 3L),
                      val1 = c(10L, 3L, 2L, 7L, 10L, 3L, 2L),
                      val2 = c(8L, 4L, 8L, 5L, 8L, 4L, 8L),
                      val3 = c(7L, 5L, 6L, 9L, 7L, 5L, 6L)),
                 .Names = c("group1", "group2", "val1", "val2", "val3"),
                 class = "data.frame", row.names = c(NA, -7L))

Ideally, I want to have two graphs based on group1(two for levels a and b) and within each group1 variable I need line charts based on the row variables(basically connecting three points for val1, val2, and val3) with different colors for different group2 variables.

回答1:

Do you mean something like this:

dat2 <- with(dat, data.frame(group1 = rep(group1, each = 3), 
                             group2 = factor(rep(group2, each = 3)), 
                             values = stack(dat[,3:5])[,1]))

The above code restructures the data into a format more easily used with ggplot. dat was defined using the dput() code I added to your Q. The plot I think you want can be produced via

p <- ggplot(dat2, aes(x = 1:3, y = values, colour = group2)) + geom_line() + 
        geom_point() + facet_wrap(~ group1, ncol = 2)
p

which gives

I've basically had to make up some x data otherwise how do you know where in the x- and y-coordinate space the points should be located?



标签: r ggplot2