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.