返回r中每个因子级别的图

时间:2013-02-22 16:09:32

标签: r plot sapply

我想为数据框“轨迹”中的每个单独ID生成X,Y图:

**trajectories**

X    Y    ID
2    4     1
1    6     1
2    4     1
1    8     2
3    7     2
1    5     2
1    4     3
1    6     3
7    4     3

我使用代码:

sapply(unique(trajectories$ID),(plot(log(abs(trajectories$X)+0.01),log((trajectories$Y)+0.01))))

但自从错误以来,这似乎不起作用:

Error in match.fun(FUN) : 
c("'(plot(log(abs(trajectories$X)+0.01),log((trajectories$Y)' is not a function,      character or symbol", "'    0.01)))' is not a function, character or symbol")

有没有办法重写这段代码,以便为每个ID获得一个单独的图?

3 个答案:

答案 0 :(得分:4)

您可以很好地使用ggplot2包:

library(ggplot2)
trajectories <- structure(list(X = c(2L, 1L, 2L, 1L, 3L, 1L, 1L, 1L, 7L), Y = c(4L, 6L, 4L, 8L, 7L, 5L, 4L, 6L, 4L), ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L)), .Names = c("X", "Y", "ID"), class = "data.frame", row.names = c(NA, -9L))

ggplot(trajectories, aes(x=log(abs(X) + 0.01), y=log(Y))) + 
  geom_point() + 
  facet_wrap( ~ ID)

为什么它的价值,你的鳕鱼失败的原因正是错误所说的。 sapply的第二个参数需要是一个函数。如果将绘图代码定义为函数:

myfun <- function(DF) {
  plot(log(abs(DF$X) + 0.01), log(DF$Y))
}

但这不会将您的数据拆分为ID。您还可以使用plyrdata.table包进行拆分和绘图,但是您需要将图形写入文件,否则它们将在创建每个新图时关闭。

答案 1 :(得分:1)

lattice包在这里很有用。

library(lattice)
# Make the data frame
X <- c(2,1,2,1,3,1,1,1,7) 
Y <- c(4,6,4,8,7,5,4,6,4)   
ID <- c(1,1,1,2,2,2,3,3,3)
trajectories <- data.frame(X=X, Y=Y, ID=ID)

# Plot the graphs as a scatter ploy by ID
xyplot(Y~X | ID,data=trajectories)

# Another useful solution is to treat ID as a factor
# Now, the individual plots are labeled
xyplot(Y~X | factor(ID),data=trajectories)

答案 2 :(得分:0)

即使是基本的R这也是可能的。使用虹膜数据集:

WorksheetFunction