Вопрос

I want to produce an X,Y plot for each separate ID from the dataframe 'trajectories' :

**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

I use the code:

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

But this does not seem to work since the error:

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")

Is there a way to rewrite this code so that i get a separate plot for each ID?

Это было полезно?

Решение

You can use the ggplot2 package for this nicely:

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)

For what its worth, the reason your cod is failing is exactly what the error says. the second argument to sapply needs to be a function. If you define your plot code as a function:

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

But this will not split your data on ID. You could also use the plyr or data.table package to do this splitting and plotting but you will need to write the plots to a file or they will close as each new plot is created.

Другие советы

The lattice package is useful here.

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)

Even the with basic R this is possible. Using the iris Dataset:

coplot(Sepal.Length ~ Sepal.Width | Species, data = iris)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top