我需要使用以下数据创建一个简单的线图:
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
我可以轻松地使用GGPLOT:
library(ggplot2)
#GGPLOT
qplot(x=x, y=y,
data=test,
colour=group,
main="GGPLOT line plot with groups") +
geom_line()
我也可以用TRELLIS做到:
library(lattice)
xyplot(y~x,
type="b",
group=group,
data=test,
main="TRELLIS line plot with groups",
auto.key =list(
lines = TRUE)
)
但是,我现在有点不愿意使用GGPLOT或TRELLIS。我希望能够用Base R创建这个图。我可以让这个图在Base R中工作的唯一方法是使用for循环:
# set up empty plot
plot(test$y ~test$x, ylab="y", xlab="x", type="n", main="Base R line plot with groups")
colors<-c("red","blue")
#plot each group in the for loop
number_of_groups <- as.numeric(max(unique(test$groupcd))) #calculate number of groups
for (i in 1:number_of_groups)
{
temp <- subset(test, groupcd==i )
lines(temp$x, temp$y, col=colors[i])
points(temp$x, temp$y, col=colors[i])
}
legend("top", legend=unique(test$group), text.col =colors )
这种方法似乎很复杂。在基地R有更简单的方法吗?基础R绘图功能中是否有组选项?非常感谢你。
答案 0 :(得分:8)
这样的事情可以作为工作的基础:
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
xvals <- split(test$x,test$group)
yvals <- split(test$y,test$group)
plot(1:max(unlist(xvals)),ylim=(c(0,max(unlist(yvals)))),type="n")
# thanks to @BenBolker for refining this next key line
mapply(lines,xvals,yvals,col=c("red","blue"),pch=1:2,type="o")
结果:
答案 1 :(得分:2)
使用MATPLOT的不同方法:
library(reshape)
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1","Group 2"),3),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
colors<-c("red","blue")
#Transform data to wide format
test_transposed<-reshape(test,
idvar='x',
drop="group",
timevar="groupcd",
direction="wide")
colors<-c("red","blue")
#drop x column
test_transposed$x<-NULL
matplot(test_transposed,
type = "b",
ylab="y",
col=colors,
main="MATPLOT with groups",
pch = 1:2)
legend("top",
legend=unique(test$group),
lty=1:2,
col=colors,
pch=1:2 )
答案 2 :(得分:1)
我也想知道这一点。我的面板数据没有完全覆盖x轴(年),因此矩阵式解决方案可能会变得复杂。相反,我去了......
mytest = data.frame(
x = rep(1:3, each = 2),
groupcd= rep(c(1,2),3),
y= c(22,8,11,4,7,5)
)
mytest = rbind(mytest,c(2,3,15),c(3,3,17))
plottables <- split(mytest,mytest$groupcd)
plot(y~x,dat=plottables[[1]],type="l",xlim=range(mytest$x),ylim=range(mytest$y))
lapply(plottables,function(z)points(y~x,dat=z,type="l"))