我有以下代码:
library("ggplot2")
data <- data.frame(c(0,1,2,3,4,5), c(-0.2, 0.6, 2.1, 3.8, 6.05, 7.6))
colnames(data) <- c("X", "Y")
f1 <- function(x)
{
x - 0.2
}
f2 <- function(x)
{
ifelse(x>=1.9,-2+x+0.1,0)
}
m <- function(x)
{
f1(x) + f2(x)
}
graph <- ggplot(data, aes(X,Y, colour="Data")) + geom_point(stat = "identity") + xlim(c(0,5))
graph <- graph + scale_shape_discrete(name = "Data")
g1 <- stat_function(fun=f1, linetype="dashed", aes(colour="Function A"))
g2 <- stat_function(fun=f2, linetype="dashed", aes(colour="Function B"))
gm <- stat_function(fun=m, aes(colour="Model"))
graph <- graph + g1 + g2 + gm
graph <- graph + scale_colour_manual(values = c("black", "red", "red", "red"))
print(graph)
产生以下图表:
图例中并不能真正区分各种功能。我宁愿期待像这样的传奇:
是否有可能生产类似的东西?
答案 0 :(得分:2)
这是一种(稍微丑陋)的可能性:
ggplot(data, aes(x = X, y = Y, colour = "Data")) +
geom_point() +
geom_line(aes(linetype = "Data"), alpha = 0) +
stat_function(fun = f1, aes(colour = "Function A", linetype = "Function A")) +
stat_function(fun = f2, aes(colour = "Function B", linetype = "Function B")) +
stat_function(fun = m, aes(colour = "Model", linetype = "model")) +
scale_linetype_manual(values = c("blank", "dashed", "dashed", "solid"),
guide = FALSE) +
scale_colour_manual(values = c("black", "red", "red", "red"),
guide = guide_legend(override.aes = list(
linetype = c("blank", "dashed", "dashed", "solid"),
size = c(2, 0, 0, 0)),
title = NULL))
我为&#34; Data&#34;创建了一个空白虚拟线。积分(geom_line
[...] alpha = 0
);将linetype
移至aes
内,移除linetype
传奇(scale_linetype_manual
[...] guide = FALSE
);使用linetype
更改了size
并在图例中指向guide_legend(override.aes
。