Search code examples
ggplot2legendrocauc

R: linetype and color manual not showing in ggplot legend


I'm plotting the following data (stored as data.frame object) as ROC-AUC plot using ggplot. I want to display each data in unique linetype and color and arrange them into a legend inside the plot, so I referenced this thread, but my code (at below) doesn't seem to work. Linetype and color are just not showing on the legend. If will be really appreciated if someone could point out the error in my code or suggest alternative way to achieve the desired result.

library(ggplot2)

df1 <- readRDS(url("https://www.dropbox.com/s/rtkyjs4af9h0qhx/df1.rds?dl=1"))
df2 <- readRDS(url("https://www.dropbox.com/s/r3qlvm36ybxqpcz/df2.rds?dl=1"))
df3 <- readRDS(url("https://www.dropbox.com/s/ebd8vu3l8iefzcz/df3.rds?dl=1"))
df4 <- readRDS(url("https://www.dropbox.com/s/cud2g0xijcc5cql/df4.rds?dl=1"))
df5 <- readRDS(url("https://www.dropbox.com/s/pzaznhozuxywnuc/df5.rds?dl=1"))
df6 <- readRDS(url("https://www.dropbox.com/s/n8ryyboznmxf1dq/df6.rds?dl=1"))


ggplot() + 
  geom_line(data = df1, aes(X3, X2, col = "Model 1: 76.9", linetype = "Model 1: 76.9"), size = 1.1, alpha=0.8) + 
  geom_line(data = df2, aes(X3, X2, col = "Model 2: 78.3", linetype = "Model 2: 78.3"), size = 1.1, alpha=0.8) + 
  geom_line(data = df3, aes(X3, X2, col = "Model 3: 77.2", linetype = "Model 3: 77.2"), size = 1.1, alpha=0.6) + 
  geom_line(data = df4, aes(X3, X2, col = "Model 4: 77.3", linetype = "Model 4: 77.3"), size = 1.1, alpha=0.6) + 
  geom_line(data = df5, aes(X3, X2, col = "Model 5: 78.5", linetype = "Model 5: 78.5"), size = 1.1, alpha=0.4) + 
  geom_line(data = df6, aes(X3, X2, col = "Model 6: 78.5", linetype = "Model 6: 78.5"), size = 1.1, alpha=0.4) + 
  scale_color_manual(name = "       Model  AUC", 
                     values = c("Model 1: 76.9" = "#F8766D", "Model 2: 78.3" = "#F8766D", "Model 3: 77.2" = "#00BFC4", "Model 4: 77.3" = "#00BFC4", "Model 5: 78.5" = "#00BFC4", "Model 6: 78.5" = "#00BFC4")) +
  scale_linetype_manual(name = "       Model  AUC", values = c("Model 1: 76.9" = "solid", "Model 2: 78.3" = "dotted", "Model 3: 77.2" = "solid", "Model 4: 77.3" = "dotted", "Model 5: 78.5" = "dashed", "Model 6: 78.5" = "dotdash")) +
  labs(title="ROC AUC", x ="1 - Specificity (%)", y = "Sensitivity (%)") +
  theme_bw() + scale_x_continuous(labels = c(0, 25, 50, 75, 100)) +
  theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.80, 0.35))
pic


Solution

  • If this is only happening in your plot panel, try ggsave for example.

    In my plot panel, it looked the same as in your picture:

    enter image description here

    However, after saving it in a folder, I get colors and linetypes:

    enter image description here