Adding legend to ggpolt with geom_line()

I have been working with this code for a while and have had no luck on getting the legend to appear. I have looked at other examples online but have not been able to apply it for my code. I am working on creating a power curve and need to show each of the line structures in the legend.

delta <- c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2)
prop <- c(5.1662, 7.0713, 11.5492, 19.4394, 28.9774, 40.4647, 55.004, 67.6677, 79.0875)
cs <- c(5.22, 7.26, 10.44, 17.86, 26.18, 36.8, 49.9, 62.22, 69.7674)
ex <- c(22.58, 24.98, 33.88, 44.84, 57.8, 69.78, 79.88, 88.8, 93.32)
un <- c(18.44, 19.82, 25.16, 34.36, 42.52, 53.96, 65.2, 75.02, 83.64)
alpha <- c(5, 5, 5, 5, 5, 5, 5, 5, 5)

n50 <- tibble(delta, prop, cs, ex, un, alpha)

p50 <- n50 %>%
ggplot() +
geom_line(aes(x = delta, y = prop), linetype = "solid") +
geom_line(aes(x = delta, y = cs), linetype = "dashed") +
geom_line(aes(x = delta, y = ex), linetype = "twodash") +
geom_line(aes(x = delta, y = un), linetype = "longdash") +
geom_line(aes(x = delta, y = alpha), color = "gray") +
xlab("Simulated Difference") +
ylab("Power of the Test") +
ylim(0,100) +
ggtitle("n=50") +
theme_bw()

p50

The easiest way to have a legend added automatically is to reshape the data accordingly:

library(tidyverse)
n50 %>% 
  pivot_longer(-delta) %>% 
  ggplot(aes(x = delta, y = value, linetype = name)) + 
  geom_line() + 
  scale_linetype_manual(
    values = c(
      prop = "solid", 
      cs = "dashed", 
      ex = "twodash", 
      un = "longdash", 
      alpha = "dotted"
    )
  ) + 
  labs(
    title = "n=50", 
    x = "Simulated Difference", 
    y = "Power of the Test", 
    linetype = "(description)"
  ) + 
  ylim(0,100) + 
  theme_bw()

You could also add a colour aesthetic for alpha, but to simplify I made it dotted here instead.

1 Like

Hi @AmberWhydirt,

By pivoting the table to long form it becomes a lot simpler to implement:

library(dplyr)
library(ggplot2)
library(tidyr)
  
delta <- c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2)
prop <- c(5.1662, 7.0713, 11.5492, 19.4394, 28.9774, 40.4647, 55.004, 67.6677, 79.0875)
cs <- c(5.22, 7.26, 10.44, 17.86, 26.18, 36.8, 49.9, 62.22, 69.7674)
ex <- c(22.58, 24.98, 33.88, 44.84, 57.8, 69.78, 79.88, 88.8, 93.32)
un <- c(18.44, 19.82, 25.16, 34.36, 42.52, 53.96, 65.2, 75.02, 83.64)
alpha <- c(5, 5, 5, 5, 5, 5, 5, 5, 5)

n50 <- tibble(delta, prop, cs, ex, un, alpha)

n50 %>% 
  pivot_longer(prop:alpha) %>% 
  ggplot(aes(delta, value)) +
  geom_line(aes(lty = name)) +
  xlab("Simulated Difference") +
  ylab("Power of the Test") +
  ylim(0,100) +
  ggtitle("n=50") +
  theme_bw()

Created on 2020-01-14 by the reprex package (v0.3.0)