我想绘制一些线条,让它们在颜色和线型上有区别。如果我单独区分颜色,那很好。如果我添加线型,则第14组的线会消失。
(ggplot2_2.1.0,R版本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!
发生了什么事?
答案 0 :(得分:1)
您可以通过使用十六进制字符串手动定义每一行的形式来解决它(请参阅?linetype
)。
?linetype
说;
...,字符串“33”指定三个单位,然后三个关闭 和“3313”指定三个单位,然后三个关闭,然后 一个,最后三个。
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)