0
votes

I am having difficulty adding additional linetypes to the legend for a plot I created in R using ggplot2. The code below uses continuous data for the variables Percentage.of.Total.Prescriptions.... and Percentage.Paid.Out.of.Pocket.... to attempt to create a lineplot with two sets of lines, solid and dashed, and a a respective legend.

Lineplot <- ggplot(Table.6, aes(x = Year, 
                            y = Percentage.of.Total.Prescriptions...., 
                            group = as.factor(Table.6$Insurance.Status), 
                            color = Insurance.Status,
                            linetype = "Total Insulin \nPrescriptions")) + geom_line()
Lineplot <- Lineplot + 
geom_line(aes(y = Percentage.Paid.Out.of.Pocket...., 
colour = Insurance.Status, 
linetype = "Paid \n Out-of-Pocket"), 
linetype = 5)

Lineplot <- Lineplot + labs(title = "Human Insulin Utilization")
Lineplot <- Lineplot + labs(x = "Year")
Lineplot <- Lineplot + labs(y = "Percentage (%)")
Lineplot <- Lineplot + labs(colour = "Insurance Status")
Lineplot <- Lineplot + scale_x_continuous(breaks = c(seq(2002,2015,1)))
Lineplot <- Lineplot + scale_y_continuous(breaks = c(seq(0,1,0.1)))
Lineplot <- Lineplot + expand_limits(y = 0:1)
Lineplot

Plot #1

The second block of code creates a dashed line that I attempt to label in the legend, unfortunately without luck.

I would appreciate any pointers on how to add a second linetype to the legend, representing a dashed line.

Thank you

1
I think you need scale_linetype_xxx ggplot2.tidyverse.org/reference/scale_linetype.htmlTung
Thanks for your comment, unfortunately, I already tried each variant, and was not able to get it to work. It appears as though these functions do not work with continuous data...Graveyard Orbit

1 Answers

1
votes

In the second geom_line, you're defining linetype once in the aes and then overwriting it immediately thereafter with linetype = 5. Delete that and it should work:

# dummy data
foo = data.frame(a = c(1:10),
                 b = rnorm(10, 5, 2),
                   c = rnorm(10,10,2))

# how it is now
ggplot(foo, aes(x = a, y = b, linetype = "b")) + 
  geom_line() + 
  geom_line(aes(y = c, linetype = "c"), linetype = 5)

# fixed
ggplot(foo, aes(x = a, y = b, linetype = "b")) + 
  geom_line() + 
  geom_line(aes(y = c, linetype = "c"))

Also, you can make it a little cleaner by leaving only the common aes arguments in the main ggplot bit and moving the line-specific arguments to the first geom_line:

ggplot(foo, aes(x = a)) + 
  geom_line(aes(y = b, linetype = "b")) + 
  geom_line(aes(y = c, linetype = "c"))

To specify linetypes after that, use scale_linetype_manual

ggplot(foo, aes(x = a)) + 
  geom_line(aes(y = b, linetype = "b")) + 
  geom_line(aes(y = c, linetype = "c")) + 
  scale_linetype_manual(values = c(1,5))