简体   繁体   English

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

[英]how to plot multiple plots on ggplots with lapply

library(ggplot2)
x<-c(1,2,3,4,5)
a<-c(3,8,4,7,6)
b<-c(2,9,4,8,5)

df1 <- data.frame(x, a, b)

x<-c(1,2,3,4,5)
a<-c(6,5,9,4,1)
b<-c(9,5,8,6,2)

df2 <- data.frame(x, a, b)

df.lst <- list(df1, df2)

plotdata <- function(x) {
  ggplot(data = x, aes(x=x, y=a, color="blue")) + 
    geom_point() +
    geom_line()
}

lapply(df.lst, plotdata)

I have a list of data frames and i am trying to plot the same columns on the same ggplot. 我有一个数据框列表,我试图在同一个ggplot上绘制相同的列。 I tried with the code above but it seems to return only one plot. 我试过上面的代码,但它似乎只返回一个情节。

There should be 2 ggplots. 应该有2 ggplots。 one with the "a" column data plotted and the other with the "b" column data plotted from both data frames in the list. 一个用“a”列数据绘制,另一个用“b”列数据从列表中的两个数据帧绘制。

i've looked at many examples and it seems that this should work. 我看了很多例子,看来这应该有效。

They are both plotted. 它们都是绘制的。 If you are using RStudio, click the back arrow to toggle between the plots. 如果您使用的是RStudio,请单击后退箭头以在图表之间切换。 If you want to see them together, do: 如果你想一起看到它们,请执行以下操作:

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

在此输入图像描述

If you want them on the same plot, it's as simple as: 如果你想要它们在同一个地块上,它就像这样简单:

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")

Edit: if you have several of these, you are probably better off combining them into a big data set while keeping the df of origin for use in the aesthetic. 编辑:如果你有其中的几个,你可能最好将它们组合成一个大数据集,同时保持原点的df用于美学。 Example: 例:

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM