【问题标题】:R layout() for ggplot inside functionggplot内部函数的R布局()
【发布时间】:2017-11-21 10:50:22
【问题描述】:

我有几个绘制ggplot 的通用函数。现在我想将它们组合成新的情节,但不知何故 layout() 不起作用。

我做了这个例子来说明我的观点:

plot_func_1 = function(){
  data1 <- data.frame(matrix(c(1:10), ncol=2))
  colnames(data1) <- c("name", "value")
  ggplot(data = data1) +
    geom_boxplot(aes(x = 1, y = value))
}

plot_func_2 = function(){
  data2 <- data.frame(matrix(c(11:20), ncol=2))
  colnames(data2) <- c("name", "value")
  ggplot(data = data2) +
    geom_boxplot(aes(x = 1, y = value))
}

plot_func_1_func_2_combined = function(){
  mat <- matrix(c(1,2), ncol = 2)
  layout(mat, width = c(0.5, 0.5))
  plot_func_1()
  plot_func_2()
}

plot_func_1_func_2_combined()

plot_func_1_func_2_combined() 应该将plot_func_1()plot_func_2() 组合成一张图。但相反,只显示了第二个图。我该如何改变呢?

补充信息:基本的plot函数似乎不存在这个问题,在这里它可以工作:

plot_func_1 = function(){
  plot(1:5)
}
plot_func_2 = function(){
  plot(10:15)
}

plot_func_1_func_2_combined = function(){
  mat <- matrix(c(1,2), ncol = 2)
  layout(mat, width = c(0.5, 0.5))
  plot_func_1()
  plot_func_2()
}
plot_func_1_func_2_combined()

【问题讨论】:

    标签: r function layout ggplot2


    【解决方案1】:

    尝试使用 grid.arrange() 包中的 gridExtra 而不是 layout()

    library(gridExtra)
    
    plot_func_1_func_2_combined = function(){
     grid.arrange(plot_func_1(),plot_func_2(), ncol=2)
    }
    
    plot_func_1_func_2_combined()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2019-05-02
      • 1970-01-01
      • 2020-05-27
      • 2015-12-10
      • 2013-08-27
      相关资源
      最近更新 更多