0

I would like to mark specific values on the X-axis with vertical lines and add a corresponding legend to the chart. I have added the specific lambda names to mark the vertical lines, but I would be grateful if someone could help me show me to rather display the lambda name + line type + color as a second legend.

data <- data.frame(rbind(cbind(rep("MSE train",101),
                               seq(0,1,0.01),
                               seq(0.5,0.6,0.001)),
                         cbind(rep("MSE val",101),
                               seq(0,1,0.01),
                               seq(0.35,0.45,0.001)),
                         cbind(rep("MSE test",101),
                               seq(0,1,0.01),
                               seq(0.3,0.4,0.001))))

colnames(data) <- c("MSE","Lambda","value")

data$Lambda <- as.numeric(data$Lambda)
data$value <- as.numeric(data$value)

lab_val <- expression(lambda["val"]^{"opt"})
lab_train<- expression(lambda["train"]^{"opt"})
lab_test <- expression(lambda["test"]^{"opt"})

ggplot(data, aes(x=Lambda, y=value, colour=MSE)) + 
  geom_line(size = 1.0, aes(linetype = MSE)) + theme_bw()  +
  labs(x = expression(lambda), y = expression(MSE)) +
  geom_vline(xintercept=0.1, color = "gray60") +
  geom_vline(xintercept=0.2, color = "black") +
  geom_vline(xintercept=0.3, color = "gray60", linetype = "dashed") +
  annotate("text", x=0.1, y=1.2, label=lab_val) +
  annotate("text", x=0.2, y=1.2, label=lab_test) +
  annotate("text", x=0.3, y=1.2, label=lab_train) +
  scale_colour_manual(values=c("black", "gray60", "gray60")) +
  scale_linetype_manual(values=c("solid", "dashed","solid"))
zephryl
  • 14,633
  • 3
  • 11
  • 30

1 Answers1

3

You have used up the color and linetype aesthetic already, but you could hijack the linewidth aesthetic and override its aesthetics to add another legend category:

ggplot(data, aes(x=Lambda, y=value, colour=MSE)) + 
  geom_line(size = 1.0, aes(linetype = MSE)) + theme_bw()  +
  labs(x = expression(lambda), y = expression(MSE)) +
  geom_vline(color = "gray60", aes(xintercept = 0.1, linewidth = "val")) +
  geom_vline(color = "black", aes(xintercept = 0.2, linewidth = "test")) +
  geom_vline(aes(xintercept = 0.3, linewidth = "train"),
             color = "gray60", linetype = "dashed") +
  annotate("label", x=0.1, y=1.2, label=lab_val) +
  annotate("label", x=0.2, y=1.2, label=lab_test) +
  annotate("label", x=0.3, y=1.2, label=lab_train) +
  scale_colour_manual(values=c("black", "gray60", "gray60")) +
  scale_linetype_manual(values=c("solid", "dashed","solid")) +
  scale_linewidth_manual("Optimal", values = c(0.5, 0.5, 0.5)) +
  guides(linewidth = guide_legend(override.aes = list(
    color = c("gray60", "black", "gray60"), linetype = c(1, 1, 2)),
    byrow = TRUE)) +
  theme(legend.spacing.y = unit(5, "mm"))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87