GGPLOT2绘制属于不同组的虚线的颜色相同实线线(ggplot2 draw dashed line

2019-09-01 15:22发布

我想绘制两种不同的颜色为每个组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"))

Answer 1:

要添加虚线你应该添加2 geom_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)))



文章来源: ggplot2 draw dashed lines of same colour as solid lines belonging to different groups
标签: r ggplot2