R ggplot with two series: points and errorbars with legends

前端 未结 2 606
鱼传尺愫
鱼传尺愫 2021-01-17 02:02

If I have a dataframe like this:

obs<-rnorm(20)
d<-data.frame(year=2000:2019,obs=obs,pred=obs+rnorm(20,.1))
d$pup<-d$pred+.5
d$plow<-d$pred-.5
d$         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 02:49

    Here is one solution melting pred/obs into one column. Can't post image due to rep.

    library(ggplot2)
    obs <- rnorm(20)
    d <- data.frame(dat=c(obs,obs+rnorm(20,.1)))
    d$pup <- d$dat+.5
    d$plow <- d$dat-.5
    d$year <- rep(2000:2019,2)
    d$lab <- c(rep("Obs", 20), rep("Pred", 20))
    
    p1<-ggplot(data=d, aes(x=year)) +
    geom_point(aes(y = dat, colour = factor(lab), shape = factor(lab))) +
    geom_errorbar(data = d[21:40,], aes(ymin=plow,ymax=pup), colour = "blue") +
    scale_shape_manual(name = "Legend Title", values=c(6,1)) +
    scale_colour_manual(name = "Legend Title", values=c("red", "blue"))
    p1
    

    enter image description here

    edit: Thanks for the rep. Image added

提交回复
热议问题