在ggplot2中的单个图上绘制3个变量

时间:2015-11-12 13:42:32

标签: r plot ggplot2

您有一个由三个变量组成的实验,我想将它们全部绘制在一个图上。

这是我的df:

AB <- data.frame(block=c("A", "A", "A", "A", "B", "B", "B", "B" ),
  familiarity=c("fam", "fam", "unfam", "unfam" ),
  prime=c("P", "UP" ),
  RT=c("570.6929", "628.7446", "644.6268", "607.4312", "556.3581", "645.4821", "623.5624", "604.4113"))

现在我只能将其中一个变量分成两个独立的图,如下所示,其中A和B是第三个变量的两个级别:

A <- AB[which(AB$block == "A"),]
B <- AB[which(AB$block == "B"),]

pa <- ggplot(data=A, aes(x=prime, y=RT, group=familiarity)) +
  geom_line(aes(linetype=familiarity), size=1) +
  expand_limits(y=c(500,650))

pb <- ggplot(data=B, aes(x=prime, y=RT, group=familiarity)) +
  geom_line(aes(linetype=familiarity), size=1) +
  expand_limits(y=c(500,650))

我想在图B上叠加图A,并将第三个变量用颜色标识。

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

这是你的意思吗?

p_all <- ggplot(AB, aes(x=prime,y=RT,group=interaction(familiarity,block))) +
  geom_line(aes(linetype=familiarity,color=block)) 

enter image description here

使用的数据:

AB <- structure(list(block = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L), .Label = c("A", "B"), class = "factor"), familiarity = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), class = "factor", .Label = c("fam", 
"unfam")), prime = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L
), class = "factor", .Label = c("P", "UP")), RT = c(570.6929, 
628.7446, 644.6268, 607.4312, 556.3581, 645.4821, 623.5624, 604.4113
)), .Names = c("block", "familiarity", "prime", "RT"), row.names = c(NA, 
-8L), class = "data.frame")

答案 1 :(得分:0)

如果这些变量有不同的数据集,则可以指定数据

String ChargeCompany1Cnt=CompanyData.split(,)[0].replace("{","");
String ChargeCompany2Cnt=CompanyData.split(,)[1];
String ChargeCompany3Cnt=CompanyData.split(,)[2];
String BalanceCompany3Cnt=CompanyData.split(,)[3];
String ChargeCompany1Flag=CompanyData.split(,)[8];