Home > Back-end >  Show rounded decimal places as label in ggplot2
Show rounded decimal places as label in ggplot2

Time:03-16

I'm trying to make a plot with odds ratios including the actual values, rounded to the second decimal. I did try different solutions from other threads including the format and the sprintf-functions. Unfortunately, they do not work for my code, potentially due to the structure of my ggplot-commands. I would really appreciate a hint on how to solve the problem. Here is the example and the code I'm working with:

or<-as.numeric(c(1.909783, 1.536364, 2.787936, 1.898587, 1.216597, 1.350239))
lwr.ci<-as.numeric(c(1.4197895,1.1336468, 1.9416681, 1.0845309, 0.8674560, 0.6554979))
upr.ci<-as.numeric(c(2.568880, 2.082142, 4.003045, 3.323680, 1.706263, 2.781314))
n<-c(419,260,153,53,182, 31)
names<-as.factor(c("a","b","c","d","e","f"))
plab<-c("***","**","***","*","","")


ex<-as.data.frame(cbind(or,lwr.ci,upr.ci,n,names,plab))

ex$or<-as.numeric(ex$or)
ex$lwr.ci<-as.numeric(ex$lwr.ci)
ex$upr.ci<-as.numeric(ex$upr.ci)

p1 <- ggplot(ex, aes(or, fct_rev(names))) 
  theme_bw(base_family = "Times New Roman",base_size =24)

p1<-p1 geom_vline(aes(xintercept = 1), size = .5, linetype = 'dashed')  
  geom_errorbarh(aes(xmax =ifelse(upr.ci<13,upr.ci,13), xmin = lwr.ci), size = 2, height = 0, color = 'gray')  
  geom_point(size = 4, color = 'black')   
  theme(panel.grid = element_blank())  
  scale_x_continuous(breaks = c(0:13),limits = c(-3,13)) 
  ylab('CL')  
  xlab('Odds Ratios') 
  ggtitle('title') 
  geom_text(parse=T,aes(label=paste(sprintf("%.2f",round(or,2)),sep ="","(","italic(n)==",n,")")),x= -1.5, size = 8,color='black',family="Times New Roman") 
  geom_text(aes(label=plab),vjust=-0.5,fontface='bold', size=8)
p1

Thanks in advance.

CodePudding user response:

When you are parsing an expression, put single quotes around the %.2f in your sprintf string to show a fixed number of digits:

p1   
  geom_vline(aes(xintercept = 1), size = .5, linetype = 'dashed')  
  geom_errorbarh(aes(xmax = ifelse(upr.ci < 13, upr.ci, 13), xmin = lwr.ci), 
                 size = 2, height = 0, color = 'gray')  
  geom_point(size = 4, color = 'black')  
  theme(panel.grid = element_blank())  
  scale_x_continuous(breaks = c(0:13), limits = c(-3,13))  
  ylab('CL')  
  xlab('Odds Ratios')  
  ggtitle('title')  
  geom_text(aes(label = paste(sprintf("'%.2f'", or), "  (", "italic(n)==", n ,")")), 
                x= -1.5, size = 8, color = 'black', family = "Times New Roman",
            parse = TRUE)  
  geom_text(aes(label = plab), vjust = -0.5, fontface = 'bold', size = 8)

enter image description here

  • Related