Convert scientific notation +e to 10^(y) with superscripts in geom_text

Viewed 1552

I want to add data labels on top of each bar. But instead of +e i would like it to be in 10^ format. There is a lot of literature out for axes. None for labels. My code is given below:

    amino.acids<-c(rep("Lysine",4),rep("Tryptophan",4),rep("Valine",4))
Source<-(rep(c("Cow","Cat","Monkey","Human"),3))
Values<-c(46846813,3186186135,6816135168,3178168,
          461351,681684351,3584684351,68463513511,
          8463510351,8435186468,1358486,6843513065)

df<-data.frame(Source,amino.acids,Values)

ggplot(df, aes(x=reorder(Source, -Values),y=Values, fill=Source))+
  geom_bar(stat = "identity", color="black")+
  facet_wrap(~amino.acids)+
  scale_y_log10(label = trans_format("log10",math_format(10^.x)))+
  xlab("")+ylab("Transformations Potential (Qu/Ha)")+
  theme(axis.text.x = element_text(angle = 45, hjust=1),
        legend.position = "none")

adding geom_text(label = trans_format("log10",math_format(10^.x))) fails.

2 Answers

You need to set the breaks as well in scale_y_log10.

library(ggplot2)
library(scales)

ggplot(df, aes(x=reorder(Source, -Values),y=Values, fill=Source))+
  geom_bar(stat = "identity", color="black")+
  facet_wrap(~amino.acids)+
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), 
                labels = trans_format("log10", scales::math_format(10^.x)))+
  xlab("")+ylab("Transformations Potential (Qu/Ha)")+
  theme(axis.text.x = element_text(angle = 45, hjust=1),
        legend.position = "none")

enter image description here

We may write a small helper function expSup which uses sprintf and does the math for scientific notation with superscripts.

expSup <- function(w, digits=0) {
  sprintf(paste0("%.", digits, "f*x*10^%d"), w/10^floor(log10(abs(w))), floor(log10(abs(w))))
}

Your plot,

library(ggplot2)
library(scales)
p <- ggplot(df, aes(x=reorder(Source, -Values), y=Values, fill=Source)) +
  geom_bar(stat="identity", color="black") +
  facet_wrap(~amino.acids) +
  scale_y_log10(label=trans_format("log10",math_format(10^.x))) +
  xlab("") + 
  ylab("Transformations Potential (Qu/Ha)") +
  theme(axis.text.x=element_text(angle=45, hjust=1), legend.position="none") 

now with labels on the bars:

p + geom_text(label=parse(text=expSup(Values)), vjust=-.25, size=3)

enter image description here

Throws a warning, but who cares.

Related