繁体   English   中英

使用Apply函数创建多个折线图(ggplot),并根据其列名为其命名

[英]Creating multiple line graphs (ggplot) using Apply function and giving them titles based on their column names

我有一个数据框,其中包含在不同时间点的不同期限的债券收益率。

例如,我的数据框看起来像这样

bond_duration <- c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr", "ten_yr")
Jan_2007 <- c(3.12, 2.98, 3.01, 3.07, 3.11, 3.18)
Feb_2007 <- c(2.93, 2.89, 2.91, 2.99, 3.02, 3.08)
Mar_2007 <- c(2.62, 2.53, 2.51, 2.70, 2.79, 2.91)
df <- as.data.frame(cbind(bond_duration, Jan_2007, Feb_2007, Mar_2007))
df[, 2:4] <- apply(df[, 2:4], 2, as.numeric)

第一列包含具有不同持续时间的债券。 在接下来的三列(第2至4列)中,它显示了特定时间点(例如2007年1月)的每个债券的收益率。

我要实现的是使用Apply函数根据每个时间点内找到的数据创建多个折线图(例如,2007年1月所有债券期限的收益率的折线图,2月所有债券期限的收益率的折线图2007等)。

我的x轴将是不同的债券期限,而我的y轴将是收益率。

我可以使用以下代码成功绘制每个时间点的收益曲线:

ggplot(data, aes(x = bond_duration, y = Jan_2007, group = 1)) + geom_point() + geom_line() + 
scale_x_discrete(limits = c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr", 
                            "ten_yr")) + 
ggtitle(paste(colnames(data)[2], " Yield Curve", sep = "")) +ylab("Yield (%)")

但是,当我尝试使用Apply函数为每个时间点循环创建多个折线图时,我的脚本起作用了。 该脚本能够为每个时间点创建多个折线图,但是每个折线图的标题都相同。 我使用以下代码:

apply(data, 2, function(x) ggplot(data, aes(x = bond_duration, y = x, group = 1)) + geom_point() + geom_line() + 
      scale_x_discrete(limits = c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr", 
                                  "ten_yr")) + 
      ggtitle(paste(colnames(data)[x], " Yield Curve", sep = "")) + ylab("Yield (%)"))

我怀疑代码的ggtitle部分出了问题。 我希望将每个折线图命名为(particular_timepoint)_yield曲线。

任何帮助表示赞赏。 谢谢!

使用上述数据框df ,将创建一个包含3个图的列表p

p <- lapply(names(df)[2:4], function(x) {
  ggplot(df, aes_string(x = "bond_duration", y = x, group = 1)) + 
   geom_point() + 
   geom_line() + 
   scale_x_discrete(limits = c("three_mth", "one_yr", "two_yr", "five_yr", 
                               "seven_yr", "ten_yr")) + 
   ggtitle(paste0(x, " Yield Curve")) + ylab("Yield (%)")
})

您可以使用双括号语法p[[i]]访问每个图。

lapply函数将三个月中的每个月的列名作为字符串传递,因此您需要在ggplot函数中使用aesaes_string变体来使其识别要传递给它的内容。

您可能需要考虑将数据重整形为整齐的格式(将month变量gather到一列中),并使用ggplot facet_wrap函数生成1个图,每个月都分成自己的图面,如下所示:

tidy_df <- df %>% 
  gather(Month, Yield, 2:4) %>% 
  mutate(bond_duration = factor(bond_duration, levels = c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr", "ten_yr")),
         Month = factor(Month, levels = c("Jan_2007", "Feb_2007", "Mar_2007")))

ggplot(tidy_df, aes(bond_duration, Yield, group = Month)) +
  facet_wrap(~ Month, ncol = 1) +
  geom_point() +
  geom_line() +
  labs(title = "Bond Duration Yield Curve by Month", x = "Bond Duration", y = "Yield (%)")

暂无
暂无

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

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