将ggplot对象保存在循环中 [英] Save ggplot objects in loop

查看:105
本文介绍了将ggplot对象保存在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,所以对不起,如果问题很蠢,但我环顾四周,找不到答案:

I am new to R so sorry if the question is dumb, but I have looked around and can't find an answer:

我有一个面板数据集,其中包含24个月内25家银行的贷款数据.在这里,我用3个银行和3个期间创建了一个更简单的版本:

I have a panel dataset with loan data for 25 banks over a period of 24 months. Here I make a simpler version with 3 banks and 3 periods:

bank<-c("bank1", "bank1", "bank1", "bank2", "bank2", "bank2",   "bank3", "bank3", "bank3")

date<-c("jan-2016", "feb-2016", "Mar-2016", "jan-2016", "feb-2016","Mar-2016", "jan-2016", "feb-2016", "Mar-2016")

tot_loans<-c(200000, 100000, 200000, 155000, 233000, 435000, 99000,   111000, 129000)

df<-data.frame(bank, date, tot_loans) 

我想创建一个循环,为每个库保存ggplot对象.我的目标是稍后在markdown文件中使用这些对象.我尝试这个:

I'd like to create a loop that saves ggplot objects for each bank. My goal is to use these objects later in a markdown file. I try this:

bank_list <- unique(df$bank)

 for (i in seq_along(bank_list)) { 
     paste(i, "total_loans", sep="_") <- df %>%
     group_by(date) %>%
     filter(bank==[[i]]) %>%
     ggplot(aes(x=date, y=loan_size)) +
          geom_line() +
          ggtitle(paste([[i]], "value of loans", sep=" "))
   }

但是这里有多个错误.我想得到的是一系列名为"bank1_total_loans","bank2_total_loans"等的ggplot对象,它们每个都具有银行名称作为ggplot标题. 有办法吗?

But there are multiple errors here. What I would like to get is a series of ggplot objects called "bank1_total_loans", "bank2_total_loans" etc, and each of them has the bank name as ggplot title. Is there a way to do this?

推荐答案

library(ggplot2)

library(dplyr)

library(zoo)

将日期变量转换为Date类以进行适当的可视化.

Transforming date variable into Date class for proper visualisation.

df$date <- as.yearmon(as.character(df$date), "%b-%Y")
df$date <- as.Date(df$date)

ggplot_creater <- function(data, selector){
    m <- data %>% filter(bank %in% selector) %>%
    ggplot(aes(x=date, y=tot_loans, group=bank)) +
    theme_bw(base_size=14)+
    geom_line() +
    labs(x="Date", y="Total of Loans",
         title="Value of loans")+
    facet_wrap(~bank)
}

让我们看看它的效果如何:

Let's see how well it works:

bank1_total_loans <- ggplot_creater(df, "bank1")
bank1and3_total_loans <- ggplot_creater(df,c("bank1", "bank3"))

这篇关于将ggplot对象保存在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆