2017-08-11 57 views
2

我想有一个与多行两个水平方面对类似这样的数据:ggplot:2面多行

  Date variable  value 
1 2016-08-04 sd6  0.01197055 
2 2016-08-05 sd6  0.01188592 
3 2016-08-08 sd6  0.01179797 
4 2016-08-04 sd12  0.01263279 
5 2016-08-05 sd12  0.01263080 
6 2016-08-08 sd12  0.01263223 
7 2016-08-04 sd24  0.01074460 
8 2016-08-05 sd24  0.01074747 
9 2016-08-08 sd24  0.01074515 
10 2016-08-04 lcorr6 0.83422880 
11 2016-08-05 lcorr6 0.83598720 
12 2016-08-08 lcorr6 0.83666730 
13 2016-08-04 lcorr12 0.83777470 
14 2016-08-05 lcorr12 0.83803200 
15 2016-08-08 lcorr12 0.83790820 

我一定要添加其他列,以确定sdlcorr或者我可以如果不这样做呢?我心目中的情节是这样的:

enter image description here

实际结构是:

structure(list(Date = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("2016-08-04", "2016-08-05", 
"2016-08-08"), class = "factor"), variable = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("rollsd6", 
"rollsd12", "rollsd24", "rollcorr6", "rollcorr12"), class = "factor"), 
    value = c(0.011970547, 0.011885922, 0.011797967, 0.012632791, 
    0.012630795, 0.01263223, 0.010744599, 0.010747466, 0.010745155, 
    0.8342288, 0.8359872, 0.8366673, 0.8377747, 0.838032, 0.8379082 
    )), row.names = c(NA, -15L), .Names = c("Date", "variable", 
"value"), class = "data.frame") 
+1

尝试'facet_grid',您可以在其中指定每个维度。你可能需要制作第二个变量,你可以在其中识别'sd'和'lcorr',是的。 –

+0

谢谢@RomanLuštrik。任何想法如何从“变量”列中只提取'sd'和'lcorr'? – AK88

+1

请以易于粘贴的形式提供您的数据(例如使用'dput'),我可以向您展示。 –

回答

3

这里是你如何提取有关sdcorr和使用facet_grid绘制。请注意,我使用了scale = "free_y",这使得构面的可比性更差。

library(ggplot2) 

xy <- structure(list(Date = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
             2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("2016-08-04", "2016-08-05", 
                        "2016-08-08"), class = "factor"), variable = structure(c(1L, 
                                      1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("rollsd6", 
                                                       "rollsd12", "rollsd24", "rollcorr6", "rollcorr12"), class = "factor"), 
        value = c(0.011970547, 0.011885922, 0.011797967, 0.012632791, 
           0.012630795, 0.01263223, 0.010744599, 0.010747466, 0.010745155, 
           0.8342288, 0.8359872, 0.8366673, 0.8377747, 0.838032, 0.8379082 
        )), row.names = c(NA, -15L), .Names = c("Date", "variable", 
                  "value"), class = "data.frame") 

xy$group_variable <- gsub("\\d+$", "", xy$variable) 
xy$group_sd <- as.factor(gsub("[[:alpha:]]", "", xy$variable)) 
xy$Date <- as.Date(xy$Date, format = "%Y-%m-%d") 

ggplot(xy, aes(x = Date, y = value)) + 
    theme_bw() + 
    geom_line() + 
    facet_grid(group_variable ~ group_sd, scale = "free_y")