我想使用循环来为不同的DPC值创建多个图。我看到的数据如下:
df <- data.frame (c ("Results", "Capacity", "Power", "LDI","LDE", "LB", "PDC","D", CostPerkWh)
作为输出,我想要多个带有图表的图表,用于PDC的每个唯一值。 以下情节有效:
plot1 <- ggplot(subset(df, df$PDC=='PDC0'),
aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
plot2 <- ggplot(subset(df, df$PDC=='PDC0.25'),
aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
plot3 <- ggplot(subset(df, df$PDC=='PDC0.5'),
aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
plot4 <- ggplot(subset(df, df$PDC=='PDC0.75'),
aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
plot5 <- ggplot(subset(df, df$PDC=='PDC1'),
aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
所有这些图都有效,但我想创建一个循环,因为我有大量的参数,我找到了这个example。
所以我试着将它实现到我自己的模型中:
#plot data
StoreResults <- "/Users/IMA/Documents/Results/"
PDC.graph <- function(df, na.rm = TRUE, ...){
PDClist <- unique(df$PDC)
for (i in seq_along(PDClist)){
plot <-
ggplot(subset(df, df$PDC==PDClist[i]),
aes(Capacity, CostPerkWh)) + geom_point()+
ggtitle(paste(PDClist, 'PDC, Power \n', "Capacity \n", sep='')) +
geom_line()
print(plot)
#save plot as PNG
ggsave(plot, file= paste(StoreResults, '/projection_graphs/PDCgraph/',
PDClist[i], ".png", sep=''), scale=2)
}
}
代码没有给我一个错误消息,但是我没有看到任何图形,也没有任何内容存储到定义的文件夹中;怎么解决这个?或者有更好的方法导出不同的PDC值的图形?
答案 0 :(得分:1)
你没有忘记运行你创建的功能吗? 这个最小版本适合我:
df = iris
StoreResults <- "/Users/timfaber/Desktop"
PDC.graph <- function(df, na.rm = TRUE, ...){
PDClist <- unique(df$Species)
for (i in seq_along(PDClist)){
ggplot(subset(iris, df$Species==PDClist[i]),
aes(Sepal.Length, Sepal.Width)) + geom_point() +
ggtitle(paste(PDClist[i], 'PDC, Power \n', "Capacity \n", sep=''))
#save plot as PNG
ggsave(plot = last_plot(), file= paste(StoreResults, '/etc/',
PDClist[i], ".png", sep=''), scale=2)
}
}
PDC.Graph(df)