簡體   English   中英

如何編寫一個函數來循環變量並使用 ggplot 繪圖

[英]How to write a function to loop through variables and plot using ggplot

我在弄清楚如何遍歷數據框中的變量並使用 ggplot 繪制它們時遇到問題。 我的數據示例如下:

head(myData,2)

          x1        x2      yhat        x11        x3    yhat1        x12
1 -0.8523122 -2.737223 -6.562228 -0.8523122 -1.450288 0.464739 -0.8523122
2 -0.5649950 -2.737223 -6.562228 -0.5649950 -1.450288 0.464739 -0.5649950
         x4     yhat2       x21       x31      yhat3
1 -1.267759 -4.624147 -2.737223 -1.450288 -0.6858007 
2 -1.267759 -4.624147 -2.267001 -1.450288 -0.6858007 

我想要做的是使用geom_raster繪制每對變量(即 [x1,x2],[x11,x3] 等)並使用相應的 yhat 作為fill值。

例如,如果我要手動繪制所有內容,我會執行以下操作:

p<-ggplot(myData, aes(x = x1, y = x2)) + geom_raster(aes(fill = yhat))
pp<-ggplot(myData, aes(x = x11, y = x3)) + geom_raster(aes(fill = yhat1))
ppp<-ggplot(myData, aes(x = x12, y = x4)) + geom_raster(aes(fill = yhat2))
pppp<-ggplot(myData, aes(x = x21, y = x31)) + geom_raster(aes(fill = yhat3))

grid.arrange(p, pp, ppp, pppp, ncol = 2)

但是我正在嘗試編寫一個函數來遍歷數據框並繪制圖形。 我試着去適應從不同問題的代碼在這里,但我不能讓它為我工作。

關於如何為我的數據實現這一目標的任何建議?

一種方法是每 3 列拆分數據並將代碼應用於每個列表。

library(gridExtra)
library(tidyverse)
library(rlang)

 temp <- split.default(df, gl(ncol(myData)/3, 3)) %>%
      map(~{
      x <- syms(names(.))
      ggplot(., aes(x = !!x[[1]], y = !!x[[2]])) + geom_raster(aes(fill = !!x[[3]]))
     })
grid.arrange(grobs = temp)  

在此處輸入圖片說明

數據

將此應用於 2 行的有限數據。

myData <- structure(list(x1 = c(-0.8523122, -0.564995), x2 = c(-2.737223, 
-2.737223), yhat = c(-6.562228, -6.562228), x11 = c(-0.8523122, 
-0.564995), x3 = c(-1.450288, -1.450288), yhat1 = c(0.464739, 
0.464739), x12 = c(-0.8523122, -0.564995), x4 = c(-1.267759, 
-1.267759), yhat2 = c(-4.624147, -4.624147), x21 = c(-2.737223, 
-2.267001), x31 = c(-1.450288, -1.450288), yhat3 = c(-0.6858007, 
-0.6858007)), class = "data.frame", row.names = c("1", "2"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM