17

我正在尝试为每组以 2 种不同颜色绘制 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,分组部分再次没有运气......</p>

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"))
4

1 回答 1

44

要添加虚线,您应该添加 2geom_line()调用,在其中提供 y 值aes()。不需要放置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)))

在此处输入图像描述

于 2013-05-01T14:50:09.110 回答