0

I am having difficulty adding my legend back to my graph while using geom_line() command in R. Here is some reproducible data:

df <- data.frame(Sample = c("Mesa-6X", "Mesa-6X-Cen", "Mesa-600X", "Mesa-6000X", "Mesa-6X", "Mesa-6X-Cen", "Mesa-600X", "Mesa-6000X"), 
       CO2 = c("0.810", "0.630", "1.170", "0.882", "0.720", "0.377", "0.521", "0.444"), 
       Log = c(rep(1.68, 4), rep(2.2, 4)), 
       Colors = rep(c("tomato", "blue", "darkmagenta", "black"), 2))

There are multiple posts regarding this issue of legends not showing up such as: Add legend to geom_line() graph in r, Reasons that ggplot2 legend does not appear and quite a few others; however, none of the suggestions here or other tutorials I have searched seems to work on my code.

My objective: Change the color of the lines to the df$Colors while displaying the legend that shows the color that corresponds to the df$Sample column.

My code: This code colors it fine, but the legend is missing and the geom_point() disappears.

ggplot() + 
  geom_line(data = df, 
            aes(x = Log, y = CO2), 
            size = 1.2, 
            color = df$Colors, 
            group = df$Sample) +
  geom_point(color = "black", 
             size = 1.2)

My code: This code adds a legend no problem, but it refuses to color it by the df$Colors column and it colors it by default instead - which is a rainbow type of color. Here, geom_point() works. just fine. The graph I'm looking to make is this graph, but with the proper colors for the lines.

ggplot(df, 
       aes(x = Log, 
           y = CO2, 
           color = df$Colors, 
           group = Sample)) + 
  geom_line(data = df, 
            aes(color = df$Sample), 
            size = 1.2) + 
  geom_point(color = "black", size = 1.2) 

By the way: class(df$Colors) = factor

Thank you very much for your insights and help.

mnist
  • 6,571
  • 1
  • 18
  • 41
Purrsia
  • 712
  • 5
  • 18

1 Answers1

1

Try using scale_color_manual:

color_palette <-
  c("Mesa-6X" = "tomato", "Mesa-6X-Cen" = "blue", "Mesa-600X" = "darkmagenta", "Mesa-6000X" = "black")

df %>% 
  ggplot(aes(x = Log, y = CO2, color = Sample, group = Sample), size = 1.2) + 
  geom_line() + 
  geom_point() +
  scale_color_manual(values = color_palette)
cardinal40
  • 1,245
  • 1
  • 9
  • 11
  • cardinal40: Thank you for the response; however, this code did not work. It made a graph, but all of the lines were black and there was no legend. Also, the `size = 1.2` didn't work. I even tried `scale_color_manual(values = df$Colors` to no avail. – Purrsia Oct 17 '19 at 00:56