0

I know there are quite a few questions concerning this issue, but the suggested answers could not help me.

The question is actually pretty basic. I have a two lines plot and would like to add a legend underneath the plot in two columns, so that the two symbols and description are next to each other.

Here is some code for an reproducible example:

# create the vectors
MODEL <- c(78, 47, 101)
CONTROL <- c(80, 46, 100)
Date <- seq(from= as.Date("2003-06-01"), to = as.Date("2003-08-01"), by = "month")

# combine the vectors to a data frame
my.df <- data.frame(MODEL, CONTROL, Date)

# give colnames
colnames(my.df) <- c("MODEL", "CONTROL", "Month")

# plot
ggplot(my.df, aes(x= Month)) +
  geom_line(aes(y= MODEL), color= "blue", size= 1) +
  geom_line(aes(y= CONTROL), color= "red", size= 1) +
  scale_y_continuous(limits= c(40, 110), breaks = seq(40,110,10)) +
  scale_x_date(limit=c(as.Date("2003-06-01"),as.Date("2003-08-01")), date_breaks= "1 month", date_labels = "%b") +
  ylab("CIMFD [kg/m²]") + xlab("") +
  theme_bw() + theme(text= element_text(size= 20)) +
  theme(axis.text= element_text(size= 25, color= "black")) +
  scale_colour_manual("", breaks = c("MODEL", "CONTROL"), values = c("blue", "red")) +
  theme(legend.position = "bottom") +
  guides(fill=guide_legend(ncol=2))

As you can see, there are some commands for the legend included, but the legend does not appear. I only get this output: enter image description here

So the question is, how to make the legend appear? Anybody with a hint?

climsaver
  • 341
  • 2
  • 15

1 Answers1

2

The trouble is that you didn't map your colors to the aesthetic. Try something like this?

ggplot(my.df, aes(x= Month)) +
  geom_line(aes(y= MODEL,color='Model'),  size= 1) + # change made here
  geom_line(aes(y= CONTROL, color= "Control"), size= 1) + # change made here
  scale_y_continuous(limits= c(40, 110), breaks = seq(40,110,10)) +
  scale_x_date(limit=c(as.Date("2003-06-01"),as.Date("2003-08-01")), date_breaks= "1 month", date_labels = "%b") +
  ylab("CIMFD [kg/m²]") + xlab("") +
  theme_bw() + theme(text= element_text(size= 20)) +
  theme(axis.text= element_text(size= 25, color= "black")) +
  scale_color_manual(name='Key', # Remove "Key" for no legend title
                     values = c('red','blue'))+ # change made here
  theme(legend.position = "bottom") +
  guides(fill=guide_legend(ncol=2))

enter image description here

dandrews
  • 967
  • 5
  • 18