如何在R中绘制多个水平图

时间:2018-03-10 11:33:40

标签: r plot

我正在通过AppliedPredictiveModeling,并遇到了一个没有描述它如何运作的情节。生成数据的代码是:

svmParam2 <- expand.grid(eps = c(.01, 0.05, .1, .5 ), costs= 2^c(-2, 0, 2, 8),
                     sigma = as.vector(sigest(y~x, data=sinData, frac=.75)))

for (i in 1:nrow(svmParam2)){
   rbfSVM<-ksvm(x=x, y=y, data=sinData,
           kernel="rbfdot",
           kpar=list(sigma=svmParam2$sigma[i]),
           C=svmParam2$costs[i],
           epsilon=svmParam2$eps[i])

   tmp <- data.frame(x=dataGrid$x,
                y=predict(rbfSVM, newdata=dataGrid),
                eps=paste("epsilon:", format(svmParam2$eps)[i]),
                costs=paste("cost:", (svmParam2$costs)[i]),
                sigma=paste("sigma:", format(svmParam2$sigma, digits=2)[i]))
  svmPred2 <- if(i==1) tmp else rbind(tmp, svmPred2)
}
svmPred2$costs <- factor(svmPred2$costs, levels = rev(levels(svmPred2$costs)))
svmPred2$sigma <- factor(svmPred2$sigma, levels = rev(levels(svmPred2$sigma)))

并且图表如下所示:What I want to replicate

每个图是一个规则的x,y图,有四条不同的曲线,每个sigma值一个,总共有16个不同的图,每列有不同的成本值,每行有不同的epsilon值。 / p>

1 个答案:

答案 0 :(得分:0)

一种方法是使用ggplot:

library(ggplot2)

ggplot(svmPred2)+
   geom_line(aes(x = x, y = y, color = sigma))+
   facet_grid(eps ~ costs) +
   theme_bw()

enter image description here

和格子:

library(lattice)
library(latticeExtra)

useOuterStrips(strip=strip.custom(bg = "skyblue"), 
               strip.left=strip.custom(bg = "skyblue"), 
               xyplot(y~x |costs *eps,
                      data = svmPred2,
                      type = 'l',
                      groups = sigma,
                      col = c("red","blue","green"),
                      auto.key = list(columns = 3)))

enter image description here

数据:

library(kernlab)

x <- runif(100, min=2, max=10)
y <- sin(x)+rnorm(length(x))*.25
sinData <- data.frame(x=x, y=y)
dataGrid <- data.frame(x = seq(2, 10, length = 100))

svmParam2 <- expand.grid(eps = c(.01, 0.05, .1, .5 ), costs= 2^c(-2, 0, 2, 8),
                         sigma = as.vector(sigest(y~x, data=sinData, frac=.75)))

svmPred2 <- data.frame()
for (i in 1:nrow(svmParam2)){
  rbfSVM<-ksvm(x=x, y=y, data=sinData,
               kernel="rbfdot",
               kpar=list(sigma=svmParam2$sigma[i]),
               C=svmParam2$costs[i],
               epsilon=svmParam2$eps[i])

  tmp <- data.frame(x=dataGrid$x,
                    y=predict(rbfSVM, newdata=dataGrid),
                    eps=paste("epsilon:", format(svmParam2$eps)[i]),
                    costs=paste("cost:", (svmParam2$costs)[i]),
                    sigma=paste("sigma:", format(svmParam2$sigma, digits=2)[i]))
  svmPred2 <- if(i==1) tmp else rbind(tmp, svmPred2)
}
svmPred2$costs <- factor(svmPred2$costs, levels = rev(levels(svmPred2$costs)))
svmPred2$sigma <- factor(svmPred2$sigma, levels = rev(levels(svmPred2$sigma)))