我需要创建一个函数来制作相同类型的不同ggplot2

时间:2016-07-07 09:22:58

标签: r function ggplot2

我需要帮助ggplot。 我有一个很大的数据框,包括不同年份收集的不同物种。对于每个物种和年份,有两个样本,每个样本代表长度频率分布。我需要创建一个ggplot函数来绘制不同物种,年份和样本的相同图。下面是我多次使用的一个情节的代码:

ggplot(df, aes(x=lenClass, y=Ntot, fill=Sex)) +
geom_bar(stat="identity") + 
facet_grid(Year~DayTime) + theme_bw() +
xlab('CL mm') + ylab('No.individuals') +
ggtitle("StrataN1 - Sp1") +
theme(axis.title.x = element_text(size=13),
    axis.title.y  = element_text(size=13),
    plot.title = element_text(size = 14),
    strip.text.x = element_text(size=10.5),
    strip.text.y = element_text(size=8),
    axis.text.x  = element_text(size=8.5),
    axis.text.y  = element_text(size=7.5))

非常感谢你!

1 个答案:

答案 0 :(得分:0)

诀窍是对你的课程进行循环。在循环中,您可以过滤数据并执行其他数据预处理,然后生成,显示和保存绘图。

library(ggplot2)

mainDF = iris
species = unique(mainDF$Species)
allPlots = list() #List to save plots

for(sp in species){ # For each class

  filteredDF = mainDF[mainDF$Species == sp,] # Filter dataframe  
  spPlot = ggplot(filteredDF, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle(sp) # Generate plot
  plot(spPlot) # Direct plotting
  allPlots[[sp]] = spPlot # Save plot to list

}