[英]R: How to plot 4 graphs using a loop statement with the plot function
我有以下代碼可以創建一個圖,數據位於此處Data
data<-lidar
x<-lidar$range
y<-lidar$logratio
h<-20
par(mfrow=c(2,2))
r<-max(x)-min(x)
bn<-ceiling(r/h)
binwidth=c(5,10,30,100)
#Creates a matrix to handle the data of same length
W<-matrix(nrow=length(x),ncol=bn)
for (j in 1:bn){
for (i in 1:length(x)){
if (x[i]>=(min(x)+(j-1)*h) && x[i]<=(min(x)+(j)*h)){W[i,j]=1}
else {W[i,j]=0}
}
}
#Sets up the y-values of the bins
fit<-rep(0,bn)
for (j in 1:bn){
fit[j]<- sum(y*W[,j]/sum(W[,j]))
}
#Sets up the x values of the bins
t<-numeric(bn)
for (j in 1:bn){
t[j]=(min(x)+0.5*h)+(j-1)*h
}
plot(x,y)
lines(t,fit,type = "S", col = 1, lwd = 2)
這會在頁面的左角創建一個圖,因為我有
par(mfrow=c(2,2))
有沒有辦法創建一個 for 語句,該語句將使用 5,10,30,100 的 h 值(變量 binwidth 提供的值)在該頁面上為我繪制 4 個圖形,因此我不必手動更改我的 h 值每次重現一個新的情節,所以我的最終結果是這樣的,
本質上,我想使用另一個 for 語句以不同的 h 值運行代碼 4 次,該語句繪制所有 4 個結果,而無需我一直更改 h。 非常感謝任何幫助或提示。
這是一個完全可重現的示例,它直接從 url 加載數據,然后使用apply
系列遍歷不同的圖
lidar <- read.table(paste0("http://www.stat.cmu.edu/%7Elarry",
"/all-of-nonpar/=data/lidar.dat"),
header = TRUE)
par(mfrow = c(2, 2))
breaks <- lapply(c(5, 10, 30, 100), function(i) {
val <- seq(min(lidar$range), max(lidar$range), i)
c(val, max(val) + i)})
means <- lapply(breaks, function(i) {
vals <- tapply(lidar$logratio,
cut(lidar$range, breaks = i, include.lowest = TRUE), mean)
c(vals[1], vals)})
invisible(mapply(function(a, b) {
plot(lidar$range, lidar$logratio)
lines(a, b, type = "S", lwd = 2)
}, breaks, means))
由reprex 包(v0.3.0) 於 2020 年 9 月 25 日創建
直接回答您的問題:保持相同的其他參數:
data<-lidar
x<-lidar$range
y<-lidar$logratio
h<-20
par(mfrow=c(2,2))
r<-max(x)-min(x)
bn<-ceiling(r/h)
binwidth=c(5,10,30,100)
做一個繪圖功能(不是必需的,但很好的做法)
doplot = function(h){
#Creates a matrix to handle the data of same length
W<-matrix(nrow=length(x),ncol=bn)
for (j in 1:bn){
for (i in 1:length(x)){
if (x[i]>=(min(x)+(j-1)*h) && x[i]<=(min(x)+(j)*h)){W[i,j]=1}
else {W[i,j]=0}
}
}
#Sets up the y-values of the bins
fit<-rep(0,bn)
for (j in 1:bn){
fit[j]<- sum(y*W[,j]/sum(W[,j]))
}
#Sets up the x values of the bins
t<-numeric(bn)
for (j in 1:bn){
t[j]=(min(x)+0.5*h)+(j-1)*h
}
plot(x,y)
lines(t,fit,type = "S", col = 1, lwd = 2)
}
然后循環h
參數
for(h in c(5,10,30,100)){
doplot(h)
}
一般評論:您可以通過學習如何使用 data.frames、一些dplyr
或data.table
和ggplot2
來實現這一點。 我覺得你可以用 10 條更容易理解的行來復制你的整個代碼 + 圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.