使用gridExtra从列表创建ggplot图形网格

时间:2017-02-19 00:25:30

标签: r ggplot2 gridextra

我尝试创建自动图表功能,并在ggplot2使用grid.arrange

列出set.seed(1234) df <- data.frame(rep(NA,20)) for (i in 1:6) df[,i] <- rnorm(20, 0, 3) names(df) <- paste("a", 1:6, sep = "") 列表中的图表时遇到一些问题

这里的玩具数据

gFunct <- function (vec, note = NULL) {
  if(is.null(note)) {
  g <- ggplot(df, aes_string(vec)) + geom_histogram()
  return(g)
  } else {
  g <- ggplot(df, aes_string(vec)) + geom_histogram() + annotate("text", x = 0, y = 3, label = note)
  return(g)
  }
}

现在创建一个基于参数存在与否的偶然性的简单图形函数,在这种情况下是否将一个音符添加到图形中(注意:我这样做是为了表示我的真实工作流程尽可能接近

nameList <- names(df)
noteList <- list(a1 = NULL, a2 = "hey", a3 = "hey there", a4 = NULL, a5 = NULL, a6 = "there")

现在创建两个列表

foreach

现在通过library(foreach) gg <- foreach(x = nameList, y = noteList) %do% gFunct(x,y) 函数

将这些列表传递给图表功能
gg

当我们致电[[idx]]时,我们得到的是由grid.arrange编制索引的图表列表。我想知道两件事

(1)如何将这些传递到only 'grobs' allowed in "gList"而不需要在图形函数中将它们转换为grobs。目前,我收到一条错误消息ggplot2,但在其他情况下,我无需将grid.arrange图转换为grobs以将其传递到grid.arrange

(2)除了grob问题外,有没有办法将整个列表传递到gridExtra::grid.arrange(gg, ncol = 3) 而无需手动列出每个图表?换句话说,我希望能够用

创建图表矩阵
gridExtra::grid.arrange(gg[[1]], gg[[2]], gg[[3]], gg[[4]], gg[[5]], gg[[6]], ncol = 3)

而不是

import sys,os
from math import *
import random
from numpy import *
import matplotlib.pyplot as plt
import datasets

waitForEnter=False
def exampleDistance(x1, x2):
    dist = 0.
    for i,v1 in x1.iteritems():
        v2 = 0.
        if x2.has_key(i): v2 = x2[i]
        dist += (v1 - v2) * (v1 - v2)
    for i,v2 in x2.iteritems():
        if not x1.has_key(i):
            dist += v2 * v2
    return sqrt(dist)

def computeDistances(data):
    #N = len(data)
    #D = len(data[0])
    N, D = data.shape
    dist = []
    for n in range(N):
        for m in range(n):
            dist.append( exampleDistance(data[n],data[m])  / sqrt(D))
    return dist
Dims = [784]
#Cols = ['#FF0000', '#880000', '#000000', '#000088', '#0000FF']
Cols = ['#FF0000']
Bins = arange(0, 1, 0.02)


plt.xlabel('distance / sqrt(dimensionality)')
plt.ylabel('# of pairs of points at that distance')
#plt.title('dimensionality versus uniform point distances')
plt.title('dimensionality versus digits data point distances')

for i,d in enumerate(Dims):
    distances = computeDistances(datasets.DigitData.X)
    print "D=%d, average distance=%g" % (d, mean(distances) * sqrt(d))
    plt.hist(distances,
             Bins,
             histtype='step',
             color=Cols[i])
    if waitForEnter:
        plt.legend(['%d dims' % d for d in Dims])
        plt.show(False)
        x = raw_input('Press enter to continue...')


plt.legend(['%d dims' % d for d in Dims])
plt.savefig('fig.pdf')
plt.show()

1 个答案:

答案 0 :(得分:5)

gridExtra::grid.arrange(grobs = gg, ncol = 3)