簡體   English   中英

填充 R 時堆疊直方圖會改變比例

[英]stacked histogram changes scale when filled in R

我用這種性質的數據創建了一個堆疊直方圖:

    > 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加了fill:

    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 比例,但我無法弄清楚如何獲得與黑白圖相同比例的圖。

不太確定發生了什么。 我最好的猜測是變換僅適用於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 包(v0.3.0) 於 2020 年 10 月 18 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM