Генерация множества мульти-сюжетов на основе одного набора данных в R - PullRequest
0 голосов
/ 18 октября 2018

У меня есть следующий набор данных, который содержит данные для многократных прогонов для каждого отдельного класса (т. Е. Только в следующих двух прогонах для каждого класса):

Class   Total_individuals   1   2   3   4   5
A       1000                10  6   8   5   2
A       1000                3   9   1   2   5
B       1000                7   2   6   4   8
B       1000                1   9   8   2   5
C       1000                6   4   2   8   7
C       1000                9   1   5   4   8

Я хотел бы сгенерировать мульти-график, который содержит один график для каждого класса, как показано ниже:

enter image description here

На этом графике показаны данные для первый запуск из трех классов:

A      10   6   8   5   2
B      7    2   6   4   8
C      6    4   2   8   7

Затем я хотел бы сгенерировать еще один мультиплот для данных второго запуска , которые:

A      3    9   1   2   5
B      1    9   8   2   5
C      9    1   5   4   8

Для этого я написал следующий скрипт R:

####################################
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }

  if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}
###################################
library(readr)
library(reshape2)
library(dplyr)
library(ggplot2)
library(scales)

dataset <- read_csv("/home/adam/Desktop/a.csv")
YaxisTitle <- "Fitness"


dataset <- dataset %>% melt(id.vars = c("Class"))
dataset <- subset(dataset, variable != "Total_individuals")
dataset <- transform(dataset, value = as.numeric(value))

myplots <- list()  # new empty list
for (x in unique(dataset$Class)){
  p2_data <- dataset %>% filter(Class == x)
  pp2 <- p2_data %>% ggplot(aes(x=variable, y=value, group=Class, colour=Class)) + 
    geom_line() + 
    scale_x_discrete(breaks = seq(0, 5, 1)) + 
    labs(x = as.character(p2_data$Class), y = YaxisTitle) + 
    theme(text = element_text(size=10),legend.position="none")

  myplots[[i]] <- pp2
  i <- i+1
}

xx <- multiplot(myplots[[1]], myplots[[2]], myplots[[3]], cols=2)

png(filename="/home/adam/Desktop/name.png")
plot(xx)
dev.off()

Но этот скрипт дает мне следующий сюжет:

enter image description here

, который объединяет все данные всех прогонов на одном графике.

Итак, я хочу создать один мультиплот для каждого прогона для трех классов.

1 Ответ

0 голосов
/ 18 октября 2018

Использование фасетов: изменение формы от широкого к длинному, добавление значений x и runN , затем построение графиков с фасетами:

# example data
df1 <- read.table(text = "Class   Total_individuals   1   2   3   4   5
A       1000                10  6   8   5   2
A       1000                3   9   1   2   5
B       1000                7   2   6   4   8
B       1000                1   9   8   2   5
C       1000                6   4   2   8   7
C       1000                9   1   5   4   8", header = TRUE)

library(ggplot2)
library(tidyr)


plotDat <- df1 %>% 
  group_by(Class) %>% 
  mutate(runN = paste0("run_", row_number())) %>% 
  gather(key = "k", value = "v", -c(Class, Total_individuals, runN)) %>% 
  group_by(Class, runN) %>% 
  mutate(x = row_number())

Фасет по идентификатору прогона:

ggplot(plotDat, aes(x, v, col = Class)) +
  geom_line() +
  facet_grid(.~runN)

enter image description here

Или фасет для идентификатора прогона и класса:

ggplot(plotDat, aes(x, v, col = Class)) +
  geom_line() +
  facet_wrap(.~runN + Class, ncol = length(unique(plotDat$Class)))

enter image description here

Или даже лучшая версия, как упоминается в комментариях @Axemen:

ggplot(plotDat, aes(x, v, col = Class)) +
  geom_line() +
  facet_grid(runN ~ Class)

enter image description here

...