Say I have a dataset where I have a categorical variable where the categories are of two different fundamental types: for instance, that one of them represents the total of the values from the other two categories. I can encode this by a separate categorical variable, say is_total
.
library(tidyverse)
dat <- tribble(
~x, ~y, ~categorical, ~is_total,
0, 0, "A", FALSE,
1, 1, "A", FALSE,
0, 1, "B", FALSE,
1, 3, "B", FALSE,
0, 1, "Total", TRUE,
1, 4, "Total", TRUE
)
I then want to create a line plot, where the total is shown with one type of line and the two components are shown with another type of line, and all three lines have different colours. I can do that like this:
ggplot(dat, aes(x, y, colour = categorical, linetype = is_total))
geom_line()
The problem is that I don't want two legends: I want "Total" to be shown with a dashed line in the second legend (and then I can get rid of the legend for is_total
using guides(linetype = FALSE)
). How would I do that? (I hoped changing the titles to be the same using labs
would make it work things out, but sadly not.)
CodePudding user response:
One option would be to map categorical
on linetype
too and set your desired linotypes via scale_linetype_manual
:
library(tidyverse)
dat <- tribble(
~x, ~y, ~categorical, ~is_total,
0, 0, "A", FALSE,
1, 1, "A", FALSE,
0, 1, "B", FALSE,
1, 3, "B", FALSE,
0, 1, "Total", TRUE,
1, 4, "Total", TRUE
)
ggplot(dat, aes(x, y, colour = categorical, linetype = categorical))
geom_line()
scale_linetype_manual(values = c(A = "solid", B = "solid", Total = "dashed"))