如何使用ggplot2和刻度将轴标签从科学格式更改为幂格式?

我正在ggplot中创建图表,并希望将x轴刻度从科学格式更改为10 ^ n,20 ^ n,30 ^ n等格式,而无需将轴更改为对数刻度。我已经从该线程的注释部分复制了代码:

How can I format axis labels with exponents with ggplot2 and scales?

并对此稍作改动:

scale_x_continuous(label= function(x) {ifelse(x==0,"0",parse(text=gsub("[+]","",gsub("e","^",scientific_format()(x)))))} )

这给了我刻度轴标签,形式为1 ^ n,2 ^ n,3 ^ n等。有没有办法将其更改为10 ^ n,20 ^ n,30 ^ n等(显然为n-1 )?

非常感谢。

yzg338 回答:如何使用ggplot2和刻度将轴标签从科学格式更改为幂格式?

这符合您的需求吗?

library(scales)
library(ggplot2)
library(stringr)
library(magrittr)

my_format <- function(x){
  g <- scientific_format()(x) %>% 
    stringr::str_split("e\\+") %>% 
    unlist() %>% 
    as.numeric()
  paste0(g[1],"0^",g[2]-1)
}

ggplot(dd,aes(x,y)) + 
  geom_point()+
  scale_x_continuous(label= function(x) {
    ifelse(x==0,"0",parse(text = my_format(x))
           )
    } )
,

多摆弄代码之后,我想出了以下解决方案:

scale_x_continuous(label= function(x) {ifelse(x==0,parse(text=gsub("[+]","",gsub("e","0^4",gsub("05",scientific_format()(x))))))} )

我的x轴刻度值的格式设置为0、1 ^ 5、2 ^ 5和3 ^ 5。该代码在第一个数字之后添加一个零,并将“ 5”替换为“ 4”,这样我现在得到0、10 ^ 4、20 ^ 4和30 ^ 4作为我的x轴刻度值。

希望这对人们有帮助!应该有可能使代码适应所需的任何功率值。

本文链接:https://www.f2er.com/3109261.html

大家都在问