如何用lapply在ggplots上绘制多个图

时间:2015-07-03 03:25:51

标签: r ggplot2

function(memo) {
  var collection = getContext().getCollection();
  var collectionLink = collection.getSelfLink();
  var row = {
    a: 1,
    b: 2
  };

  if ((memo != null ? memo.remaining : void 0) == null) {
    throw new Error('generateData must be called with an object containing a `remaining` field.');
  }
  if (memo.totalCount == null) {
    memo.totalCount = 0;
  }
  memo.countForThisRun = 0;

  createMemo();

  function createMemo() {
    var isAccepted = collection.createDocument(collectionLink, row, function(err, createdDoc) {
      if (err) throw err;

      memo.remaining--;
      memo.countForThisRun++;
      memo.totalCount++;

      if (memo.remaining > 0) {
        createMemo();
      } else {
        getContext().getResponse().setBody(memo);
      }
    });

    if (!isAccepted) {
      getContext().getResponse().setBody(memo);
    }
  }
};

我有一个数据框列表,我试图在同一个ggplot上绘制相同的列。我尝试使用上面的代码,但它似乎只返回一个图。

应该有2个ggplots。一个与" a"列数据绘制,另一个用" b"从列表中的两个数据帧绘制的列数据。

我看了很多例子,看起来这应该有效。

2 个答案:

答案 0 :(得分:4)

他们都被绘制了。如果您使用的是RStudio,请单击后退箭头以在图表之间切换。如果你想一起看到它们,请执行:

library(gridExtra)
do.call(grid.arrange,lapply(df.lst, plotdata))

enter image description here

答案 1 :(得分:3)

如果你想在同一块情节中使用它们,那就简单了:

ggplot(data = df1, aes(x=x, y=a), color="blue") + 
  geom_point() +
  geom_line() +
  geom_line(data = df2, aes(x=x, y=a), color="red") +
  geom_point(data = df2, aes(x=x, y=a), color="red")

编辑:如果你有其中的几个,你可能最好将它们组合成一个大数据集,同时保持原点的df用于美学。例如:

df.lst <- list(df1, df2)

# put an identifier so that you know which table the data came from after rbind
for(i in 1:length(df.lst)){
  df.lst[[i]]$df_num <- i
}
big_df <- do.call(rbind,df.lst) # you could also use `rbindlist` from `data.table`

# now use the identifier for the coloring in your plot
ggplot(data = big_df, aes(x=x, y=a, color=as.factor(df_num))) + 
    geom_point() +
    geom_line() + scale_color_discrete(name="which df did I come from?")
    #if you wanted to specify the colors for each df, see ?scale_color_manual instead

enter image description here