Reputation: 305
My apologies if this is a duplicate. I've read a number of posts about annotating individual facets. This seems to be the closest to my problem but I can't seem to make this happen with my data. I'd like to add slightly smaller font labels to the min and max of the confidence intervals in each facet. Any nudges in the right direction would be most appreciated, I'm just getting rolling with ggplot. Thanks so much.
library(ggplot2)
library(gridExtra)
Outcome<-c(1,1,1,2,2,2,3,3,3)
OR<-c(1.97,2.47,3.56,1.73,2.25,4.09,1.21,1.48,2.25)
min<-c(1.37,1.74,2.55,1.13,1.52,2.84,0.74,0.95,1.49)
max<-c(2.83,3.49,4.98,2.66,3.35,5.9,1.97,2.33,3.41)
Aces<-c(1,2,3,1,2,3,1,2,3)
ace<-data.frame(cbind(Outcome,OR,min,max,Aces))
ace2<-data.frame(min,max,Outcome,Aces)
ace_labels <- list('1'="1 ACE",'2'="2 ACEs",'3'="3 ACEs")
ace_labeller <- function(variable,value){return(ace_labels[value])}
ace$Outcome = factor(ace$Outcome, levels=c("3","2","1"),
labels=c("MH Barrier to Work: Model 3",
"MH Barrier to Work: Model 2",
"Depression: Model 1"))
p<-ggplot(data=ace,aes(x=OR,y=Outcome,label=OR))+
geom_point(aes(size=8))+
geom_text(size=5,vjust=1.75)+
geom_errorbarh(aes(xmin=min,xmax=max),height=.1)+
geom_vline(xintercept=1,linetype="dashed")+
scale_x_log10(breaks=seq(1,6,1),name="Odds Ratios (ORs) and 95% Confidence Intervals")+
labs(y="")+
facet_grid(Aces~., labeller=ace_labeller)+
guides(size=FALSE)+
theme_bw()+
theme(axis.text.y=element_text(size=12))+
theme(strip.text.y=element_text(size = 12))+
theme(axis.title.x=element_text(size = 12,hjust=.5))
#I can get one on there but can't figure out how to control it per facet
p + annotate("text", label="1.37", x =1.37, y=2.8, size=4)
#This is as close as I can get with the data frame approach
#(which is not very close at all)
ace2<-data.frame(cbind(min, Outcome,Aces))
p + geom_text(data=ace2,aes(x=min,y=2.8,label=min,inherit.aes=FALSE)) +
facet_grid(Aces~.)
Upvotes: 1
Views: 1013
Reputation: 93871
This will add labels to the min and max values of the confidence intervals:
p + geom_text(aes(label=min, x=min), vjust=1.5, size=4) +
geom_text(aes(label=max, x=max), vjust=1.5, size=4)
This works because ggplot
already has all the values it needs in the original data frame you passed to it. You just need to tell geom_text
that you want the min
and max
values used as both the text labels and the x-axis locations placing them. ggplot
takes care of the rest (i.e., the y-values and facet locations), because those are already an intrinsic part of the plot unless you override them.
Upvotes: 3