JC3019
JC3019

Reputation: 383

Add in legend to ggplot

I know this question is similar to ones that has been asked before but the suggested solutions don't seem to apply.

I set up the problem as follows

mat1 <- NULL
mat2 <- NULL
mat1 <- data.frame(matrix(nrow =16, ncol =2, data = rnorm(32, 0, 1)))
mat2 <- data.frame(matrix(nrow =16, ncol =2, data = rnorm(32, 0, 1)))
mat1[,1] = mat2[,1] = 1:16
colnames(mat1) = c("Window", "CM")
colnames(mat2) = c("Window", "FM")

ggplot() +
  geom_line(data = mat1, aes(x = mat1$Window, y= mat1$CM), linetype ="twodash", color ="steelblue") + 
  geom_line(data = mat2, aes(x = mat2$Window, y= mat2$FM), color = "black") +
  theme_classic() + xlab("Quater after alpha assessment") + ylab("Estimated Coefficient") + labs(fill = "cohort model")

I want to add in a legend. Specifically i want the blue line to be labelled as CM and the black line to be labelled as FM

Upvotes: 1

Views: 55

Answers (2)

Mojoesque
Mojoesque

Reputation: 1318

In these kind of scenarios I think it is often the easiest to bring your data into the appropriate format for ggplot. Then you can properly use all of the ggplot toolset.

library(tidyverse)

mat3 = bind_cols(mat1, mat2) %>%
  select(-Window1) %>%
  gather(type, value, -Window)

mat3 %>%
  ggplot(aes(x = Window, y = value, group = type, color = type, linetype = type)) +
  geom_line() +
  scale_color_manual("cohort model",
                     values = c("CM" = "steelblue","FM" = "black"),
                     breaks = c("CM", "FM")) +
  scale_linetype_manual("cohort model",
                        values = c("twodash", "solid"),
                        breaks = c("CM", "FM")) +
  labs(x = "Quater after alpha assessment", y = "Estimated Coefficient") +
  theme_classic()

enter image description here

Upvotes: 1

Dr. Fabian Habersack
Dr. Fabian Habersack

Reputation: 1141

I assume the simplest way to do this would be to use annote():

ggplot() +
  geom_line(data = mat1, aes(x = mat1$Window, y= mat1$CM), linetype ="twodash", color ="steelblue") + 
  geom_line(data = mat2, aes(x = mat2$Window, y= mat2$FM), color = "black") +
  theme_classic() + xlab("Quater after alpha assessment") + ylab("Estimated Coefficient") + labs(fill = "cohort model") +
  xlim(NA,18) + 
  annotate(geom="text", x=16.5, y=1.51232841, label="CM", color="blue", size=3) +
  annotate(geom="text", x=16.5, y=-0.487350382, label="FM", color="black", size=3)

You can easily change and adjust the position with x= and y=. I also slightly extended the upper limit of x-scale so that the text fits in.

Of course, I don't know if that's enough for you. Otherwise, you could also add a text field as legend. But this would be the easiest and fastest way.

enter image description here

Upvotes: 1

Related Questions