使用ggplot的apply函数绘制dataframe列的子集

时间:2018-05-08 07:03:29

标签: r ggplot2 lapply

我有一个包含许多列的数据框adb root adb remount adb shell setprop SimCheck.disable 1 ... 我想要列的子集,其中df是我想要绘制的列的列表。

我目前正在做以下

c

然而,这会产生以下错误:

df <-structure(list(Image.Name = structure(1:5, .Label = c("D1C1", "D2C2", "D4C1", "D5C3", "D6C2"), class = "factor"), Experiment = structure(1:5, .Label = c("020718 perfusion EPC_BC_HCT115_Day 5", "020718 perfusion EPC_BC_HCT115_Day 6", "020718 perfusion EPC_BC_HCT115_Day 7", "020718 perfusion EPC_BC_HCT115_Day 8", "020718 perfusion EPC_BC_HCT115_Day 9"), class = "factor"), Type = structure(c(2L, 1L, 1L, 2L, 1L), .Label = c("VMO", "VMT"), class = "factor"), Date = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "18-Apr-18", class = "factor"), Time = structure(1:5, .Label = c("12:42:02 PM", "12:42:29 PM", "12:42:53 PM", "12:43:44 PM", "12:44:23 PM"), class = "factor"),     Low.Threshold = c(10L, 10L, 10L, 10L, 10L), High.Threshold = c(255L,     255L, 255L, 255L, 255L), Vessel.Thickness = c(7L, 7L, 7L,     7L, 7L), Small.Particles = c(0L, 0L, 0L, 0L, 0L), Fill.Holes = c(0L,     0L, 0L, 0L, 0L), Scaling.factor = c(0.001333333, 0.001333333,     0.001333333, 0.001333333, 0.001333333), X = c(NA, NA, NA,     NA, NA), Explant.area = c(1.465629333, 1.093447111, 1.014612444,     1.166950222, 1.262710222), Vessels.area = c(0.255562667,     0.185208889, 0.195792, 0.153907556, 0.227996444), Vessels.percentage.area = c(17.43706003,     16.93807474, 19.29722044, 13.18887067, 18.05611774), Total.Number.of.Junctions = c(56L,     32L, 39L, 18L, 46L), Junctions.density = c(38.20884225, 29.26524719,     38.43832215, 15.42482246, 36.42957758), Total.Vessels.Length = c(12.19494843,     9.545333135, 10.2007416, 7.686755647, 11.94211976), Average.Vessels.Length = c(0.182014156,     0.153956986, 0.188902622, 0.08938088, 0.183724919), Total.Number.of.End.Points = c(187L,     153L, 145L, 188L, 167L), Average.Lacunarity = c(0.722820111,     0.919723402, 0.86403871, 1.115896082, 0.821753818)), .Names = c("Image.Name", "Experiment", "Type", "Date", "Time", "Low.Threshold", "High.Threshold", "Vessel.Thickness", "Small.Particles", "Fill.Holes", "Scaling.factor", "X", "Explant.area", "Vessels.area", "Vessels.percentage.area", "Total.Number.of.Junctions", "Junctions.density", "Total.Vessels.Length", "Average.Vessels.Length", "Total.Number.of.End.Points", "Average.Lacunarity"), row.names = c(NA, -5L), class = "data.frame")


doBarPlot <- function(x) {
  p <- ggplot(x, aes_string(x="Type", y=colnames(x), fill="Type") ) +
    stat_summary(fun.y = "mean", geom = "bar", na.rm = TRUE) +
    stat_summary(fun.data = "mean_cl_normal", geom = "errorbar", width=0.5, na.rm = TRUE) +
    ggtitle("VMO vs. VMT") +
    theme(plot.title = element_text(hjust = 0.5) )
  print(p)
  ggsave(sprintf("plots/%s_bars.pdf", colnames(x) ) )
  return(p)
}

c = c('Total.Vessels.Length', 'Total.Number.of.Junctions', 'Total.Number.of.End.Points', 'Average.Lacunarity')
p[c] <- lapply(df[c], doBarPlot)

调试显示doBarPlot中的Error: ggplot2 doesn't know how to deal with data of class numeric 属于x类型,而不是numeric,因此data.frame错误。但是,ggplot会生成test <- df2[c]类型的变量。

为什么data.framex? 在不诉诸循环的情况下应用numeric的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

正如其他人所指出的那样,初始方法的问题在于,当您在数据帧上使用lapply时,您迭代的元素将是列向量,而不是1列数据帧。但是,即使您迭代了1列数据帧,您的函数也会失败:提供给ggplot调用的数据框不会包含您在图中使用的Type列。 / p>

相反,您可以修改函数以获取两个参数:完整数据框和要在y轴上使用的列的名称。

doBarPlot <- function(data, y) {
  p <- ggplot(data, aes_string(x = "Type", y = y, fill = "Type")) +
    stat_summary(fun.y = "mean", geom = "bar", na.rm = TRUE) +
    stat_summary(
      fun.data = "mean_cl_normal",
      geom = "errorbar",
      width = 0.5,
      na.rm = TRUE
    ) +
    ggtitle("VMO vs. VMT") +
    theme(plot.title = element_text(hjust = 0.5))
  print(p)
  ggsave(sprintf("plots/%s_bars.pdf", y))
  return(p)
}

然后,您可以使用lapply迭代要绘制的列的字符向量,同时通过...将数据框作为绘图函数的固定参数提供:

library(ggplot2)

cols <- c('Total.Vessels.Length', 'Total.Number.of.Junctions',
          'Total.Number.of.End.Points', 'Average.Lacunarity')
p <- lapply(cols, doBarPlot, data = df)

此外,如果您不介意在一个文件中包含所有图表,也可以使用tidyr::gather将数据重新整形为长格式,并在图中使用facet_wrap(如建议的那样) @RichardTelford在他的评论中),完全避免了迭代和对函数的需求:

library(tidyverse)

df %>% 
  gather(variable, value, cols) %>% 
  ggplot(aes(x = Type, y = value, fill = Type)) +
    facet_wrap(~ variable, scales = "free_y") +
    stat_summary(fun.y = "mean", geom = "bar", na.rm = TRUE) +
    stat_summary(
      fun.data = "mean_cl_normal",
      geom = "errorbar",
      width = 0.5,
      na.rm = TRUE
    ) +
    ggtitle("VMO vs. VMT") +
    theme(plot.title = element_text(hjust = 0.5))

答案 1 :(得分:0)

apply系列函数可以向对象传递。一个简单的例子来说明这一点:

lapply(mtcars, function(x) print(x))

使用您的代码,您将df中每列的向量传递给函数doBarPlotggplot2包适用于数据框,而不是列表或向量,因此您会收到错误。

如果您想使用您的功能,请将其直接应用于子集df

doBarPlot(df[ , c])

如果您有一堆数据框,并且想要按c中的列进行分组,请检查此答案: How to apply same function to every specified column in a data.table

或者,请查看dplyr::select()