如何结合两个条件来制作情节?

时间:2013-07-23 17:01:46

标签: r plot ggplot2

是否可以使用两个条件绘制数据框?

我有这个数据框:

tdat=structure(list(X = structure(c(1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 
2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L), class = "factor", .Label = c("AS", 
"Dup", "MCH")), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("bot", 
"top", "all"), class = "factor"), value = c(1.009936818, 1.414634463, 
0.778023226, 1.046037598, 2.370167409, 0.714638976, 0.241778577, 
0.684398769, 0.181664019, 0.44099306, 1.212003504, 0.237309508, 
1.257632594, 2.329136359, 1.037219886, 1.495702786, 2.990687546, 
1.069762508)), .Names = c("X", "variable", "value"), row.names = c(NA, 
-18L), class = "data.frame")

> tdat
     X variable     value
1   AS      bot 1.0099368
2  MCH      bot 1.4146345
3  Dup      bot 0.7780232
4   AS      bot 1.0460376
5  MCH      bot 2.3701674
6  Dup      bot 0.7146390
7   AS      top 0.2417786
8  MCH      top 0.6843988
9  Dup      top 0.1816640
10  AS      top 0.4409931
11 MCH      top 1.2120035
12 Dup      top 0.2373095
13  AS      all 1.2576326
14 MCH      all 2.3291364
15 Dup      all 1.0372199
16  AS      all 1.4957028
17 MCH      all 2.9906875
18 Dup      all 1.0697625

我可以用

 qplot(x=variable, y=value,data=tdat). 

但是我需要使用“X”和“变量”来创建子组。所以我需要9组:AS-bot,MCH-bot,Dup-bot,AS-top等。那么有没有办法告诉qplot使用y作为y = value + X?

1 个答案:

答案 0 :(得分:2)

正如评论中已经提到的,您可以使用interaction。在这里我使用它两次2 aes。为了获得更好的图例子标题,我使用scale_color_discrete

ggplot(tdat, aes(x=interaction(X,variable,drop=TRUE,sep='-'), y=value,
                 color=X)) + 
                 geom_point() +
                 scale_color_discrete(name='interaction levels')

enter image description here