我想绘制一些线条并让它们在颜色和线型上有所区别。如果我单独区分颜色,那很好。如果我添加线型,第 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!
Run Code Online (Sandbox Code Playgroud)
这是怎么回事?
您可以通过使用十六进制字符串手动定义每行的形式来解决这个问题(请参阅 参考资料?linetype)。
?linetype说;\n\n\n\n\n...,字符串“33”指定三个单位打开,然后三个单位关闭,“3313”指定三个单位打开,然后三个单位关闭,然后\n 一个单位打开,最后三个单位关闭。
\n
HEX <- c(1:9, letters[1:6]) # can\'t use 0 \n\n ## make linetype with (two- or) four\xe2\x80\x90digit number of hex\n # In this example, I made them randomly\nset.seed(1); HEXs <- matrix(sample(HEX, 4*14, replace = T), ncol = 4)\nmy_val <- apply(HEXs, 1, function(x) paste0(x[1], x[2], x[3], x[4]))\n\n # example data\ngroup <- factor(rep(paste("Group", 1:14), each = 20), levels=paste("Group", 1:14))\ndata <- data.frame(x = 1:20, y = rep(1:14, each=20), group = group)\n\nggplot(data, aes(x = x, y = y, colour = group, linetype = group)) +\n geom_line() +\n scale_linetype_manual(values = my_val)\nRun Code Online (Sandbox Code Playgroud)\n\n\n