Plotting multiple lines R [duplicate]

2019-09-21 10:37发布

问题:

This question already has an answer here:

  • Multiple curves with same Time x-axis in R 2 answers

I have the following data:

   dim   tuples buckets error is.init
1    5 13500000      50  0.29    TRUE
2    5 13500000     100  0.28    TRUE
3    5 13500000     150  0.27    TRUE
4    5 13500000     200  0.26    TRUE
5    5 13500000     250  0.26    TRUE
6    4   360000      50  0.10    TRUE
7    4   360000     100  0.09    TRUE
8    4   360000     150  0.09    TRUE
9    4   360000     200  0.09    TRUE
10   4   360000     250  0.09    TRUE
11   3     9000      50  0.10    TRUE
12   3     9000     100  0.09    TRUE
13   3     9000     150  0.09    TRUE
14   3     9000     200  0.08    TRUE
15   3     9000     250  0.07    TRUE
16   5 13500000      50  0.48   FALSE
17   5 13500000     100  0.43   FALSE
18   5 13500000     150  0.44   FALSE
19   5 13500000     200  0.44   FALSE
20   5 13500000     250  0.43   FALSE
21   4   360000      50  0.41   FALSE
22   4   360000     100  0.39   FALSE
23   4   360000     150  0.36   FALSE
24   4   360000     200  0.37   FALSE
25   4   360000     250  0.35   FALSE
26   3     9000      50  0.31   FALSE
27   3     9000     100  0.26   FALSE
28   3     9000     150  0.25   FALSE
29   3     9000     200  0.22   FALSE
30   3     9000     250  0.20   FALSE

For each value of dim, I want two lines. One line shows error where is.init = T, and second line shows error when is.init=F. The X axis is the "buckets". It would be nice if all the lines "is.init = T" are, for instance, dashed. How do I do this? Thanks in advance.

回答1:

Something like:

library(ggplot2)
library(reshape2)
w$new <- paste(w$is.init, w$dim, sep = ".") # I named your data frame w
ggplot(data = w, aes(x = buckets, y = error, group = new)) +
geom_line(aes(linetype = is.init), size = 1) + facet_wrap(~dim)

I found almost the exact plot you needed here.



回答2:

This question is duplicated, But I trying to add a lattice solution I discover that it is not obvious to customize strip panels. Maybe I miss something, but here my code:

library(lattice) 
xyplot(error~buckets|dim,
       groups=is.init,data=dat,type='l',
       auto.key=list(columns = 2),
       strip = function(which.panel,var.name,factor.levels,...)
       {
         strip.default(..., which.panel,factor.levels,
                       var.name = paste0(var.name,factor.levels[which.panel]))
       })