我正在嘗試使用 ggplot 為不同模型繪制一些測驗錯誤,但似乎 for 回圈每次都只是替換最后一項:
library(ggplot2)
test <- data.table('obs'= rep(0,10), 'exp'=rnorm(10) ,'pred1'=rnorm(10), 'pred2'=rnorm(10), 'pred3'=rnorm(10), date=1:10)
error_plot <- ggplot() geom_point(aes(x=date, y = exp - obs), data = test, colour = "black")
pred_names <- paste0('pred', 1:3)
colours_plot <- c('green', 'blue', 'yellow', 'purple')
for (i in 1:length(pred_names)){
error_plot <- error_plot geom_point(aes(x=date, y = get(pred_names[i]) - obs), data = test, colour = colours_plot[i])
print(error_plot)
}
如果我在沒有回圈的情況下運行,一切都很好:
error_plot <- error_plot geom_point(aes(x=date, y = get(pred_names[1]) - obs), data = test, colour = colours_plot[1])
geom_point(aes(x=date, y = get(pred_names[2]) - obs), data = test, colour = colours_plot[2])
geom_point(aes(x=date, y = get(pred_names[3]) - obs), data = test, colour = colours_plot[3])
uj5u.com熱心網友回復:
由于渲染是延遲應用的,i直到渲染時才完全決議,此時i已更改。幸運的是,ggplot2也可以添加一個 geom 串列,因此我們可以使用lapply和 family 來創建一個完全“實作”的串列。根據您對迭代樣式的偏好,選擇以下選項之一:
error_plot
lapply(seq_along(pred_names), function(i) {
geom_point(aes(x = date, y = get(pred_names[i]) - obs),
data = test, colour = colours_plot[i])
})
## or ##
error_plot
Map(function(pn, cn) {
geom_point(aes(x = date, y = get(pn) - obs), data = test, colour = cn)
}, pred_names, colours_plot[1:3])
(請注意,你的pred_names短于colours_plot,ERGO需要[1:3]在Map-version)。
但也許更ggplot2規范的方法是為您的點使用長資料,這允許更少的呼叫,可選的圖例(我已在此處禁用),以及美學化變數可以完成的其他一些事情:
testlong <- melt(test, id.vars = c("date", "obs", "exp"), variable.name = "pred")
testlong
# date obs exp pred value
# <int> <num> <num> <fctr> <num>
# 1: 1 0 0.43281803 pred1 0.27655075
# 2: 2 0 -0.81139318 pred1 0.67928882
# 3: 3 0 1.44410126 pred1 0.08983289
# 4: 4 0 -0.43144620 pred1 -2.99309008
# ---
# 27: 7 0 -0.78383894 pred3 0.25792144
# 28: 8 0 1.57572752 pred3 0.08844023
# 29: 9 0 0.64289931 pred3 -0.12089654
# 30: 10 0 0.08976065 pred3 -1.19432890
# date obs exp pred value
ggplot(test)
geom_point(aes(x = date, y = exp - obs), colour = "black")
geom_point(aes(x = date, y = value - obs, colour = pred), data = testlong)
scale_colour_manual(guide = FALSE, values = setNames(colours_plot[1:3], pred_names))
我認為,在這種情況下,我們應該不使用testlong原始geom_point,因為這將增加兩倍,繪制的每個點。unique如果您想在單個框架中全押,則可以隨時緩解這種情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338252.html
