ggplot2的具有多个变量的循环函数

时间:2019-03-09 10:46:19

标签: r function for-loop ggplot2 geom-bar

我想从一个大型数据库中构建多个图,以便为每个文本(因子)和每个度量(眼动追踪研究的许多最终度量)获得一个图。以下是我要尝试的一个简单得多的示例:

假设这是我的数据集

Text <- c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2)
Position <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
Modified <- c(1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0)
Line_on_page <- c(1, 1, 1, 1, 2,2,2,2 ,1 ,1,1,1,2,2,2,2)
IA_FIXATION_DURATION <- c(250.3, 70.82, 400, 120.12, 270, 120.5, 100.54, 212.43, 250.3, 70.82, 320.29, 123.12, 260, 121.5, 100.54, 272.43)
IA_FIXATION_COUNT <- c(1,0,1,1,3,2,0, 1, 1,0,1,2,3,2,0, 2)
IA_LABEL <- c("she", "did", "not", "know", "what", "to", "say", "to", "she", "did", "not", "know", "what", "to", "do", "to")
testDF <- data.frame(Text , Position , Line_on_page, Modified, IA_FIXATION_DURATION, IA_FIXATION_COUNT, IA_LABEL)

所以我想要每个文本(1/2/3)和每个度量(IA_FIXATION_DURATION / IA_FIXATION_COUNT)的热图(或其他图形)

# so first i create my vectors


library(stringr)
library(reshape2)
library(ggplot2)
library(ggthemes)
library(tidyverse)

Text_list <- unique(testDF$Text)
Measure_list <- testDF %>% dplyr::select_if(is.numeric) %>% colnames() %>% as.vector()

# create graphing function
Heatmap_FN <- function(testDF, na.rm = TRUE, ...){

  # create for loop to produce ggplot2 graphs 
  for (i in seq_along(Text_list)) { 
    for (j in seq_along(Measure_list)) {

      # create plot for each text in dataset 
      plots <- ggplot(subset(testDF, testDF$Text==Text_list[i])) +
        geom_tile(aes(x=Position, 
                      y=Line_on_page, 
                      fill = Measure_list[j])) +
        geom_text(aes(x=Position, 
                      y=Line_on_page, 
                      label=IA_LABEL),
                  color = "white", size = 2, family = "sans") +
        scale_fill_viridis_c(option = "C", na.value = "black") +
        scale_y_reverse() +
        facet_grid(Page ~ Modified)+
        theme(legend.position = "bottom") + 
        ggtitle(paste(Text_list[i],j, 'Text \n'))

      ggsave(plots, file=paste(Measure_list[j], "_T", Text_list[i], ".pdf", sep = ""), height = 8.27, width = 11.69, units = c("in"))

    }
  }
}

Heatmap_FN(testDF)

现在,我很确定问题出在geom_tile的“填充”部分,在这里我想向函数表明我要一一使用结果变量来生成图。

关于如何解决该问题的任何想法? 谢谢

0 个答案:

没有答案