Add legend to manually added lines using ggplot

后端 未结 1 1602
猫巷女王i
猫巷女王i 2021-01-19 04:39

I\'m trying to add the corresponding legend for 3 manually added lines using ggplot. My code is the following:

library(ggplot2)
df = data.frame(         


        
1条回答
  •  囚心锁ツ
    2021-01-19 05:13

    The trick is to use appropriate mapping:

    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 讨论(0)
提交回复
热议问题