GigaByte123
GigaByte123

Reputation: 195

ggplot error bar legend

I am having difficulties adding a legend to my error bar plot. I tried several command that I've seen in other subject, but unfortunately it doesn't work (I am sure I'm missing something but I can't figure out what)

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

Upvotes: 0

Views: 2615

Answers (1)

amatsuo_net
amatsuo_net

Reputation: 2448

The problem is that you are using wide form data rather than long form data. You need to convert the data from wide to long before plotting if you want to get a 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)

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

The output looks closer to your output can be generated by:

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

Upvotes: 3

Related Questions