返回r中因子的每个级别的绘图
我想为数据帧“轨迹”中的每个单独ID生成一个X,Y图:返回r中因子的每个级别的绘图,r,plot,sapply,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)
**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获得单独的绘图?您可以使用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)
但这不会分割ID上的数据。您也可以使用plyr或data.table软件包进行分割和打印,但您需要将打印写入文件,否则在创建每个新打印时,打印将关闭。您可以使用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)
但这不会拆分ID上的数据。您也可以使用plyr或data.table软件包进行拆分和打印,但您需要将绘图写入文件,否则在创建每个新绘图时,绘图将关闭。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)
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)
即使使用基本R,这也是可能的。使用iris数据集:
coplot(Sepal.Length ~ Sepal.Width | Species, data = iris)
即使使用基本R,这也是可能的。使用iris数据集:
coplot(Sepal.Length ~ Sepal.Width | Species, data = iris)
哇,ggplot2软件包正是我需要的!非常感谢!哇,ggplot2软件包正是我需要的!非常感谢!