Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling linetype, color and label in ggplot legend

Tags:

r

ggplot2

I'm having trouble setting custom legend labels on plots where I have also previously specified custom linetypes and colors. There is a similar question on stackoverflow that deals with custom legends for linetypes and line colors. However, once you wish to specify legend labels on top of the two aforementioned attributes ggplot2 seemingly starts to break down.

Here's my minimally reproducible example:

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
           treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"))

The above code results in the following graph

Setting labels in either scale_linetype_manual or scale_color_manual results in two legends being created.

Setting labels in either scale_linetype_manual() or scale_color_manual() results in two seperate legends being created. The one that has the correct dashing of lines will always be colorless. The one with correct colors, on the other hand, will not represent the linetypes correctly (only solid lines).

Is there a way to control color, line type and legend labels all at once in ggplot2? Or is this a limitation of the package where I should just specify the labels correctly in the dataframe from the getgo?

like image 514
Lauler Avatar asked Sep 25 '17 01:09

Lauler


1 Answers

Make the label the same for both scale_linetype_manual() and scale_color_manual().

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
                 treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"),
                     labels = c("Treatment one", "Treatment two"))

enter image description here

like image 139
www Avatar answered Sep 27 '22 20:09

www