Last active
          September 25, 2023 12:26 
        
      - 
      
- 
        Save bbolker/5ba6a37d64b06a176e320b2b696b6733 to your computer and use it in GitHub Desktop. 
    scientific notation with plotmath superscripts in ggplot
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | scientific_10 <- function(x,suppress_ones=TRUE) { | |
| s <- scales::scientific_format()(x) | |
| ## substitute for exact zeros | |
| s[s=="0e+00"] <- "0" | |
| ## regex: [+]? = "zero or one occurrences of '+'" | |
| s2 <- gsub("e[+]?", " %*% 10^", s ) | |
| ## suppress 1 x | |
| if (suppress_ones) s2 <- gsub("1 %\\*% +","",s2) | |
| parse(text=s2) | |
| } | |
| ## use scale_(x|y)_continuous(labels=scientific_10, ...) | |
| ## now with lat and long | |
| library(ggplot2) | |
| ## too much repetition here ... | |
| long_label <- function(x) { | |
| s <- sprintf("%d*degree*%s", | |
| x,ifelse(x==0,"", | |
| ifelse(x<0,"W","E"))) | |
| return(parse(text=s)) | |
| } | |
| lat_label <- function(x) { | |
| s <- sprintf("%d*degree*%s", | |
| x,ifelse(x==0,"", | |
| ifelse(x<0,"S","N"))) | |
| return(parse(text=s)) | |
| } | |
| ggplot(mtcars,aes(wt,mpg)) + geom_point() + | |
| scale_x_continuous(labels=long_label) + | |
| scale_y_continuous(labels=lat_label) + | |
| labs(x="Longitude",y="Latitude") | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment