简体   繁体   English

使用ggplot2和lapply为列表中的元素分离图表

[英]Separate charts for element in list using ggplot2 and lapply

Okay guys I need a hand with using ggplot2 in a loop over a list (with lapply) to obtain a separate chart for each element of the list. 好的,我需要在列表循环中使用ggplot2(带有lapply)来获取列表中每个元素的单独图表。 I'm new to R, so forgive the noob-ness. 我是R的新手,所以请原谅。

Say I have a dataframe as such: 说我有这样一个数据框:

df <- cbind.data.frame(Time = c(1,2,3,4,1,2,3,4), 
Person = c("A","A","A","A","B","B","B","B"), 
Quantity = c(1,4,6,8,1,6,2,10))

df <- data.table(df)

> df
   Time Person Quantity
1:    1      A        1
2:    2      A        4
3:    3      A        6
4:    4      A        8
5:    1      B        1
6:    2      B        6
7:    3      B        2
8:    4      B       10

I want to produce a chart for person A and person B separately. 我想分别为人A和人B生成图表。 At the moment I have my function set up like this: 目前,我的功能设置如下:

Persons = c("A","B")
PersonList = as.list(Persons)


MyFunction <- function(x){

SubsetPersons = Persons[!(Persons %in% x)]
df <- df[!(df$Person %in% SubsetPersons)]

g <- ggplot(data=df, aes(x=Time, y=Quantity))
g <- g + geom_line()
print(g)

}

Results <- lapply(Persons, MyFunction)

But I'm not sure how to save the charts with different names corresponding to the list elements? 但是我不确定如何使用与列表元素相对应的不同名称保存图表?

NOTE: I know this function may seem an odd way to solve this problem, but for the larger more complex problem I have at hand it is required. 注意:我知道此功能似乎是解决此问题的一种奇怪方法,但是对于我手头较大的更复杂的问题,则需要此功能。 I am simply trying to figure out how to save different names for the charts in the list! 我只是想弄清楚如何为列表中的图表保存不同的名称!

Thanks in advance! 提前致谢!

Persons = c("A","B")

MyFunction <- function(x){

  dfs <- df[df$Person == x,]

  g <- ggplot(data=dfs, aes(x=Time, y=Quantity))
  g <- g + geom_line()

#have added extra bracket after ".PNG"
  ggsave(paste0("plot_for_person", x, ".PNG"), g)

  print(g)

  return(g)

}

Results <- lapply(Persons, MyFunction)

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

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