簡體   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