【问题标题】:How to set breaks in ggplot 2 scale_y_continuous(trans = "reverselog")如何在 ggplot2 scale_y_continuous(trans = "reverse log") 中设置中断
【发布时间】:2020-06-27 08:25:21
【问题描述】:

我的数据在下面

x <- c(20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 2, 3, 1, 0.5, 0.3)
y <- c(2e-42, 8e-20, 2e-15, 9e-9, 5e-7, 4e-7, 7e-5, 3e-3, 2e-2, 1e-1, 0.5, 0.3, 0.8, 5e-2, 8e-3)
data <- as.data.frame(cbind(x,y))

我想绘制 x vs y。 x 轴是 log10 缩放的,y 轴是反转的和 log10 缩放的(可以更改比例以获得更好的可视化)。我还想选择 y 轴上的中断为

我试过下面的代码

library(ggplot2)
library(metR)
ggplot(data, aes(x=x, y=y))+scale_x_log10() +scale_y_continuous(trans = "reverselog") + geom_point()

y 轴的中断不是我想要的。我尝试了下面的代码,但它不起作用。

ggplot(data, aes(x=x, y=y))+scale_x_log10() +scale_y_continuous(breaks=c(seq(2e-42, 0.0001, 0.0000001),seq(0.0001, 0.001, 0.0003),seq(0.001, 0.01, 0.003),seq(0.01, 0.05, 0.02), seq(0.05, 0.1, 0.05), seq(0.1,0.5,0.4), seq(0.5, 0.99, 0.49)),trans = "reverselog") + geom_point()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使用scales,您可以使用trans_new 来定义新的转换。 从定义变换轴的函数开始,还需要定义其逆函数。在这些函数的基础上定义了trans_new

    然后通过调用此函数coord_trans(y=log_reverse) 在 y 轴上转换图表。在以下scale_y_continuous 中断中,定义了标签和限制。

    x <- c(20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 2, 3, 1, 0.5, 0.3)
    y <- c(2e-42, 8e-20, 2e-15, 9e-9, 5e-7, 4e-7, 7e-5, 3e-3, 2e-2, 1e-1, 0.5, 0.3, 0.8, 5e-2, 8e-3)
    data <- as.data.frame(cbind(x, y))
    
    library(ggplot2)
    # library(metR)
    library(scales)
    
    lab_y <- c( "< 0.000001", "0.0001", "0.001", "0.01", "0.05", "0.1", "0.5", "1")
    brk_y <- c( 0.000001, 0.0001, 0.001, 0.01, 0.05, 0.1, 0.5, 1)
    
    
    trans <- function(x) -log(x, 10)
    inv <- function(x) -log(x, 10)
    
    log_reverse <- trans_new(name = "log reverse",
                            transform = trans,
                            inverse = inv
                            )
    
    ggplot(data, aes(x = x, y = y)) +
      geom_point() +
      scale_x_log10() +
      coord_trans(y=log_reverse) +
      scale_y_continuous(
        breaks = brk_y,
        labels = lab_y,
        limits = c(0.00000000001, 1)
      )
    
    

    PS:我个人认为带有&lt; 的刻度标签不是一个好主意。

    【讨论】:

      【解决方案2】:

      我想这就是你想要的。

      标签的外观可能需要整理:您可以使用theme(axis.text.y = element_text(size = 6)) 缩小文本大小,或者使用更少的中断。

      library(ggplot2)
      library(metR)
      library(scales)
      
      lab_y <- c( "< 0.000001", "0.0001", "0.001", "0.01", "0.05", "0.1", "0.5", "1")
      brk_y <- c( 0.000001, 0.0001, 0.001, 0.01, 0.05, 0.1, 0.5, 1)
      
      ggplot(data, aes(x=x, y=y))+
        scale_x_log10() +
        scale_y_continuous(trans = "reverselog", breaks = brk_y, labels = lab_y )+
        geom_point()
      

      reprex package (v0.3.0) 于 2020 年 6 月 27 日创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多