2014-10-05 61 views
4

我想添加3手動添加行使用ggplot相應的圖例。我的代碼如下:添加圖例使用ggplot手動添加行

library(ggplot2) 
df = data.frame(error = c(0.0832544999, 0.0226680026, 0.0082536264, 0.0049199958, 0.0003917755, 0.0003859976, 0.0003888253, 0.0003953918, 0.0003958398), sDev = c(8.188111e-03, 2.976161e-03, 1.466221e-03, 2.141425e-03, 2.126976e-05, 2.139364e-05, 2.169059e-05, 2.629895e-05, 2.745938e-05)) 

minimum <- 6 
best.model <- 5 

gplot <- ggplot(df, aes(x=1:length(error), y=error)) + 
      scale_x_continuous(breaks = seq_along(df$error)) + 
      geom_point(size = 3) + 
      geom_line() + 
      geom_errorbar(data = df, aes(x = 1:length(error), ymin = error - sDev, ymax = error + sDev), 
          width = 0.1) + 
      geom_hline(data = df, aes(yintercept = error[minimum] + sDev[minimum]), linetype = "dashed") + 
      geom_vline(xintercept = minimum, linetype = "dotted", color = "red", size = 1) + 
      geom_vline(xintercept = best.model, linetype = "dotted", color = "blue", size = 1) + 
      theme_gray(base_size = 18) + 
      theme(axis.text = element_text(color = "black")) + 
      labs(x = "# of parameters", fontface = "bold") + 
      labs(y = "CV error") + 
      labs(title = "Cross-validation error curve") 

enter image description here

我想知道如何添加傳說中的黑,紅,藍3個虛線。

非常感謝!

+0

爲什麼傳奇?爲什麼不添加一些註釋? – agstudy 2014-10-05 16:57:22

回答

6

的技巧是使用合適的映射:

gplot <- ggplot(df, aes(x=1:length(error), y=error)) + 
    scale_x_continuous(breaks = seq_along(df$error)) + 
    geom_point(size = 3) + 
    geom_line() + 
    geom_errorbar(data = df, aes(x = 1:length(error), ymin = error - sDev, ymax = error + sDev), 
       width = 0.1) + 
    geom_hline(data = df, aes(yintercept = error[minimum] + sDev[minimum], linetype="a", colour="a")) + 
    geom_vline(data= data.frame(type="b", col="b", minimum=minimum), 
      aes(linetype=type, colour=col, xintercept = minimum), size = 1, show_guide = TRUE) + 
    geom_vline(data= data.frame(type="b", col="b", best.model=best.model), 
      aes(linetype="c", colour="c", xintercept = best.model), size = 1, show_guide = TRUE) + 
    scale_colour_manual(name="Legend", values = c("a" = "black", "b" = "red", "c" = "blue")) + 
    scale_linetype_manual(name="Legend", values = c("a" = "dashed", "b" = "dotted", "c" = "dotted")) + 
    theme_gray(base_size = 18) + 
    theme(axis.text = element_text(color = "black"), 
     legend.key.height = grid::unit(0.1, "npc")) + 
    labs(x = "# of parameters", fontface = "bold") + 
    labs(y = "CV error") + 
    labs(title = "Cross-validation error curve") 

resulting plot

+0

非常感謝@羅蘭!對此,我真的非常感激!只是最後一個問題:我在函數內部使用代碼,但是這個命令有問題: geom_hline(data = df,aes(yintercept = error [minimum] + sDev [minimum],linetype =「a」 ,color =「a」)) ,因爲它無法找到最小變量。你知道如何解決這個問題嗎? – user54517 2014-10-05 17:46:07

+0

做ggplot2以外的子集。 – Roland 2014-10-05 17:51:31