ggplot错误栏图例

时间:2017-06-02 08:30:11

标签: r ggplot2 legend

我在向错误条图添加图例时遇到了困难。我在其他主题中尝试了几个命令,但不幸的是它没有用(我相信我错过了一些东西,但我无法弄清楚是什么)

library(ggplot2)

errors=matrix(c(-3.800904,-3.803444,-3.805985,-3.731204,-3.743969,
  -3.756735,-3.742510,-3.764961,-3.787413,-3.731204,-3.743969,-3.756735,
  -3.711420,-3.721589,-3.731758,-3.731204,-3.743969,-3.756735,-3.636346,
  -3.675159,-3.713971,-3.731204,-3.743969,-3.756735),nrow=4,byrow=TRUE)

modelName=c("model 1","model 2","model 3","model 0")
boxdata=data.frame(errors,modelName)
colnames(boxdata)=c("icp","pred","icm","icp_obs","obs","icm_obs","model")

qplot(boxdata$model,boxdata$pred,
     main = paste("confidance level 95% for age ", age_bp + start_age - 1,sep="")) +
  geom_errorbar(aes(x=boxdata$model, ymin=boxdata$icm, ymax=boxdata$icp), width=0.20,col='deepskyblue') +
  geom_point(aes(x=boxdata$model,y=boxdata$obs),shape=4,col="orange") + 
  geom_errorbar(aes(x=boxdata$model, ymin=boxdata$icm_obs, ymax=boxdata$icp_obs), width=0.20,col='red') +
  scale_shape_manual(name="legend", values=c(19,4)) +
  scale_color_manual(name="legend", values = c("black","orange")) +
  xlab("models") + 
  ylab("confidence level")

plot

1 个答案:

答案 0 :(得分:3)

问题是您使用的是宽格式数据而不是长格式数据。如果你想获得一个图例,你需要在绘图之前将数据从宽到长转换。

library(ggplot2)
errors=matrix(c(-3.800904,-3.803444,-3.805985,-3.731204,-3.743969,
                -3.756735,-3.742510,-3.764961,-3.787413,-3.731204,-3.743969,-3.756735,
                -3.711420,-3.721589,-3.731758,-3.731204,-3.743969,-3.756735,-3.636346,
                -3.675159,-3.713971,-3.731204,-3.743969,-3.756735),nrow=4,byrow=TRUE)

errors = rbind(errors[, 1:3], errors[,4:6]) # manually reshaping the data
modelName=c("model 1","model 2","model 3","model 0")
type = rep(c("model", "obs"), each = 4)

boxdata=data.frame(errors,modelName, type)

colnames(boxdata)=c("icp","pred","icm","model", "type")

ggplot(boxdata, aes(x = model, y = pred, ymax = icp, ymin = icm, 
                    group = type, colour = type, shape = type)) +
  geom_errorbar(width=0.20) +
  geom_point() +
  scale_shape_manual(values=c(19, 4)) +
  scale_color_manual(values = c("black","orange")) +
  xlab("models") + 
  ylab("confidence level")

输出看起来更接近您的输出可以通过以下方式生成:

ggplot(boxdata, aes(x = model, y = pred, ymax = icp, ymin = icm, 
                    group = type, colour = type, shape = type)) +
  geom_errorbar(width=0.20) +
  geom_point(colour =  rep(c("black","orange"), each = 4)) +
  scale_shape_manual(values=c(19, 4)) +
  scale_color_manual(values = c("deepskyblue", "red")) +
  xlab("models") + 
  ylab("confidence level")