【问题标题】:stacked histogram changes scale when filled in R填充 R 时堆叠直方图改变比例
【发布时间】:2021-02-01 01:40:47
【问题描述】:

我用这种性质的数据创建了一个堆叠直方图:

    > haps
        tot K7a
    1     1   2
    2     7   1
    3     1   4
    4     8   3
    5     1   6

tot 是每个元素的观察计数,(我在上表中仅显示 1899 中的 5 个元素), K7a 是一个有 7 个级别的因子。 应读取数据,例如如:元素1被观察一次属于第2组,...元素4被观察8次属于第3组,以此类推

使用以下代码,我得到一个黑白直方图:

      ggplot(haps, aes(x=tot) +
        geom_histogram(binwidth = 0.5) +
        scale_y_continuous(trans="log1p", breaks = c(1, 2, 3, 4, 5, 10, 15, 20, 25, 50, 100, 500, 1000,                 1500, 2000)) + 
        scale_x_continuous(limits = c(0, 20), breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20))+
        theme_gray(base_size = 10) + labs(x = "Haplotype repeats", y = "Number of events" ) 

然后我想给7组加颜色,我用下面的代码,简单的给aes加填充:

    ggplot(haps, aes(x=tot, fill=K7a)) +
      geom_histogram(binwidth = 0.5) +
      scale_y_continuous(trans="log1p", breaks = c(1, 2, 3, 4, 5, 10, 15, 20, 25, 50, 100, 500, 1000, 1500, 2000)) + 
      (limits = c(0, 20), breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20))+
      theme_gray(base_size = 10) + labs(x = "Haplotype repeats", y = "Number of events" ) 

即使我使用相同的代码,第二张图也会改变 y 比例,但我不知道如何获得与黑白图相同比例的图。

【问题讨论】:

    标签: r ggplot2 histogram stacked


    【解决方案1】:

    不太确定发生了什么。我最好的猜测是转换仅适用于 y 比例,而不适用于 fill 比例。
    在使用 coord_trans() 进行所有计算后,您可以应用转换来“解决”这个问题:

    library(ggplot2)
    
    df <- read.table(text="
    tot K7a
    1     1   2
    2     7   1
    3     1   4
    4     8   3
    5     1   6")
    
    ggplot(df, aes(tot, fill = factor(K7a))) +
      scale_y_continuous( breaks = c(1, 2, 3, 4, 5, 10, 15, 20, 25, 50, 100, 500, 1000,1500, 2000)) +
      geom_histogram(binwidth = 1) +
      coord_trans(y = 'log1p')
    

    reprex package (v0.3.0) 于 2020 年 10 月 18 日创建

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      相关资源
      最近更新 更多