ggplot doesn't generate legend

I realize this is probably a simple issue, but I cannot figure out why ggplot will not add a legend to my graph. I looked through the other help pages on this site concerning the same issue, but nothing I tried worked. Maybe based on my data I need to find another way to arrange things, but again, nothing I have tried has worked out. Thank you for your help!

Here is my data:

YEAR QUOTA LANDINGS
1 2000 4.0 8.0
2 2001 4.0 4.9
3 2002 4.0 4.7
4 2003 4.0 3.0
5 2004 4.0 1.5
6 2005 4.0 2.5
7 2006 4.0 6.3
8 2007 4.0 6.4
9 2008 4.0 9.0
10 2009 12.0 11.7

Here is my code:

DOGFISH <- read.csv("DOGFISH_DATA.csv", stringsAsFactors = F)
na.omit(DOGFISH)

DOGFISH_GRAPH <- ggplot() +
geom_line(data = DOGFISH, mapping = aes(x = YEAR, y = QUOTA ), color = "blue") +
geom_line(data = DOGFISH, mapping = aes(x = YEAR, y = LANDINGS), color = "red") +
labs (x = "Year", y = "Millions of Pounds", color = "Legend") +
theme(panel.background = element_blank())

DOGFISH_GRAPH

Hello @andleon,

Welcome to the forum. You're experencing this problem because you have to two geom_line functions going. Typically ggplot will only produce it automatically if you have one set. In the condition of two, you can either keep both separate and create a manual legend or you can merge it together and get it to work. Have a look here: https://rpubs.com/euclid/343644

You are right, the esiest way is to reshape your data into a long format, see this example

library(tidyverse)

# Sample data on a copy/paste friendly format
dogfish <- data.frame(
        YEAR = c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009),
       QUOTA = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 12),
    LANDINGS = c(8, 4.9, 4.7, 3, 1.5, 2.5, 6.3, 6.4, 9, 11.7)
)

dogfish %>% 
    gather(type, value, -YEAR) %>% 
    ggplot(aes(x = YEAR, y = value, color = type)) +
    geom_line() +
    labs (x = "Year", y = "Millions of Pounds", color = "Legend") +
    theme(panel.background = element_blank())

Created on 2020-09-29 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.