Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

r - ggplot2 draw dashed lines of same colour as solid lines belonging to different groups

I am trying to plot 2 solid lines in 2 different colours for each group, but also add dashed lines of the same colour around those lines, then add a legend. For some reason I am having trouble using "dashed" or "dotted", it seems as I am plotting over the dashed lines twice. I am also not getting the legend right, I get the error Adding another scale for 'colour', which will replace the existing scale.

Can you please help me figure out what I am doing wrong? Here is an example dataset and what I have tried:

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

I have also tried with geom_ribbon, again with no luck for the grouping part…

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"))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add dotted lines you should add 2 geom_line() call where you provide y values inside aes(). There is no need to put data= and groups= arguments as they are the same as in ggplot() call. linetype="dotted" should be placed outside aes() call. For the colors you need only one scale_color_manual(). To remove dotted line pattern from legend you can override aesthetic using functions guides() and 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)))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...