Home > OS >  How to change y axis labels to 10^n
How to change y axis labels to 10^n

Time:09-17

I am trying to change the y axis on my plot to 10^n. I've read a couple of post that show was to change the y axis to scientific notation (labels = scales::scientific) but that's not what I am looking for. What I want my y axis to say is 10^0, 10^1, 10^2, 10^3, 10^4, and 10^5 however I can't seem to find out how to do this.

Here is an example of my data

bar <- structure(list(pos = 1:79, val = c(68129.20691, 14216.01188, 
6390.804842, 3710.602599, 2296.736176, 1515.498656, 1032.497215, 
774.2636827, 618.9658189, 395.5689752, 287.2984833, 208.6625183, 
183.6068538, 137.6857165, 113.6463666, 96.85256149, 72.62917502, 
65.98488201, 35.93813664, 34.80700588, 37.10602599, 17.22309159, 
19.57341781, 16.15598098, 11.00694171, 7.034321639, 5.994842503, 
7.034321639, 5.994842503, 2.020949938, 4.084238653, 2.020949938, 
5.108969775, 1, 1, 2.020949938, 1, 1, 1, 0, 0, 1, 2.020949938, 
0, 2.020949938, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1), group = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", 
"B"), class = "factor")), class = "data.frame", row.names = c(NA, 
-79L))

Here is the code that I am using to make the graph

ggplot(bar, aes(pos,val, fill = group))  
  geom_bar(stat = 'identity', width = 1)   
  scale_y_continuous(trans=scales::pseudo_log_trans(base = 10),
    breaks=c(1, 10, 100, 1000, 10000, 100000),expand = c(0, 0),
  )  

  scale_x_continuous(
    minor_breaks = seq(0, 100, by = 20),
    breaks = seq(0, 100, by = 20), limits = c(0, 100),
    expand = expansion(mult = c(0, 0)),
    guide = "axis_minor"
  )  
  guides(x.sec = "axis_minor", y.sec = "axis_minor")  
  scale_fill_manual(values = alpha(c("grey", "red"), .3))  
  theme_bw()  
  theme(
    panel.border = element_rect(colour = "black", fill=NA, size=1),
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.text.x.top = element_blank(),
    axis.text.y.right = element_blank()
  )  
  annotation_logticks(sides = "lr") 

CodePudding user response:

You can set the labels in your scale_y_continuous call manually using plotmath expressions. For example, keep everything else the same, but use

scale_y_continuous(trans=scales::pseudo_log_trans(base = 10),
                   breaks=c(1, 10, 100, 1000, 10000, 100000), 
                   labels = expression(1, 10, 10^2, 10^3, 10^4, 10^5),
                   expand = c(0, 0))

and you should get a plot like this:

screenshot

  • Related