I want to plot some lines and have them differentiated on color and linetype. If I differentiate on color alone, it's fine. If I add linetype, the line for group 14 vanishes.
(ggplot2_2.1.0, R version 3.3.1)
library(ggplot2)
g <- paste("Group", 1:14)
group <- factor(rep(g, each=14), levels=g)
x <- rep(1:14, length.out=14*14)
y <- c(runif(14*13), rep(0.55, 14))
d <- data.frame(group, x, y, stringsAsFactors=FALSE)
# Next 2 lines work fine - check the legend for Group 14
ggplot(d, aes(x, y, color=group)) +
geom_line()
# Add linetype
ggplot(d, aes(x, y, color=group, linetype=group)) +
geom_line()
# Group 14 is invisible!
What's going on?
You can solve it by defining a form of each line manually with hex strings (see ?linetype
).
?linetype
says;
..., the string "33" specifies three units on followed by three off and "3313" specifies three units on followed by three off followed by one on and finally three off.
HEX <- c(1:9, letters[1:6]) # can't use 0
## make linetype with (two- or) four‐digit number of hex
# In this example, I made them randomly
set.seed(1); HEXs <- matrix(sample(HEX, 4*14, replace = T), ncol = 4)
my_val <- apply(HEXs, 1, function(x) paste0(x[1], x[2], x[3], x[4]))
# example data
group <- factor(rep(paste("Group", 1:14), each = 20), levels=paste("Group", 1:14))
data <- data.frame(x = 1:20, y = rep(1:14, each=20), group = group)
ggplot(data, aes(x = x, y = y, colour = group, linetype = group)) +
geom_line() +
scale_linetype_manual(values = my_val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With