使用Apply函数创建多个折线图(ggplot),并根据列名称给出标题

问题描述 投票:0回答:1

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

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

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部分有问题。我希望每个折线图都被命名为(special_timepoint)_yield曲线。

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

r ggplot2
1个回答
3
投票

使用上面的数据框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函数将3个月中每个月的列名称作为字符串传递,因此您需要在ggplot函数中使用aes_stringaes变体来识别传递给它的内容。

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

facet_wrap
© www.soinside.com 2019 - 2024. All rights reserved.