我试图为每组绘制2种不同颜色的实线,但也在这些线条周围添加相同颜色的虚线,然后添加图例。出于某种原因,我在使用“虚线”或“虚线”时遇到了麻烦,看起来我正在两次绘制虚线。我也没有得到正确的传说,我收到错误Adding another scale for 'colour', which will replace the existing scale
。
x <- c(10, 20, 50, 10, 20, 50)
mean = c(52.4, 98.2, 97.9, 74.1, 98.1, 97.6)
group = c(1, 1, 1, 2,2,2)
upper = c(13.64, 89, 86.4, 13.64, 89, 86.4)
lower = c(95.4, 99.8, 99.7, 95.4, 99.8, 99.7)
data <- data.frame(x=x,y=mean, group, upper, lower)
ggplot(data, aes(x = x, y= mean, group = as.factor(data$group), colour=as.factor(data$group))) + geom_line() + geom_point() + geom_line(data=data,aes(x=x, y=lower, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + geom_line(data=data,aes(x=x, y=upper, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + scale_color_manual(values=c("red", "blue")) + scale_colour_discrete(name="Groups")
我也尝试过geom_ribbon
,再次对分组部分没有运气......
ggplot(data, aes(x = x, y= mean, group = group)) + geom_line() +
geom_ribbon(aes(ymin = lower, ymax = upper)) +
geom_line(aes(y = mean), colour = "Mean")) +
scale_colour_manual(name = "", values = c("Group1", "Group2"))
答案 0 :(得分:35)
要添加虚线,您应添加2 geom_line()
次调用,在aes()
内提供y值。无需添加data=
和groups=
参数,因为它们与ggplot()
调用中的参数相同。 linetype="dotted"
应放在aes()
电话之外。对于颜色,您只需要一个scale_color_manual()
。要从图例中删除虚线图案,您可以使用函数guides()
和guide_legend()
覆盖美学。
ggplot(data, aes(x = x, y= mean, group = as.factor(data$group),
colour=as.factor(data$group))) +
geom_line() + geom_point() +
geom_line(aes(y=lower),linetype="dotted") +
geom_line(aes(y=upper),linetype="dotted")+
scale_color_manual(name="Groups",values=c("red", "blue"))+
guides(colour = guide_legend(override.aes = list(linetype = 1)))