簡體   English   中英

ggplot2:按水平因子重新排序 x 軸 label 不起作用

[英]ggplot2: reorder x axis label by factor of levels doesn't work

我想繪制一個 plot ,其x-axis標簽等於c("chr","lab1","lab3","lab10")但是當我設置x-axis的級別時,似乎x-axis的重新排序x-axis不工作。
誰能幫我解決問題? 我不知道為什么我不能更改x-axis標簽的順序。

在此處輸入圖像描述

library(ggplot2)
library(viridis)

set.seed(123)
data.df=data.frame(gene=c("APC","NF2","APC","NF2","APC","NF2","APC","NF2"),
                   variable=c("lab1","lab1","lab3","lab3","lab10","lab10","chr","chr"),
                   value=c(sample.int(100, 6),5,22))

ggplot(data.df, aes(x=factor(variable, level = c("chr",paste0("lab",c(1,3,10)))),
                    y=factor(gene, level = c("NF2","APC")))) + 
  geom_tile(data=filter(data.df,variable != 'chr'), 
            aes(fill= value),colour='white') +  
  geom_point(data = filter(data.df,variable=="chr"),
             aes(col=as.factor(value)))+ 
  scale_fill_viridis_b()

================

關於數據集的更新,我的整個數據集包括 1254 obs。 3 個變量。

設置變量級別似乎適用於本示例,但不適用於我的整個數據集。

> str(melt.df)
'data.frame':   1254 obs. of  3 variables:
 $ gene    : Factor w/ 57 levels "NF2","TNNI3",..: 29 16 39 49 18 31 9 20 52 46 ...
 $ variable: Factor w/ 22 levels "chromosome_name",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ value   : num  100 100 99.8 100 100 ...

最終更新,我找到了解決問題的方法 add + scale_x_discrete(limits = c("chr",paste0("lab",c(1,3,10))))

感謝 Ricardo Semião e Castro 和 TarJae 的幫助!

ggplot2 按其水平順序繪制任何因子變量,默認情況下,R 按字母順序設置因子的水平,因此"lab10" (以 1 開頭)位於"lab3"之前。 要更正此問題,請重新排序變量的級別:

factor(data.df$variable, c("chr","lab1","lab3","lab10")) 

另一種方法是使用0103而不是13

  • variable=c("lab01","lab01","lab03","lab03","lab10","lab10","chr","chr"),
  • level = c("chr",paste0("lab",c("01","03","10")))
library(ggplot2)
library(viridis)

set.seed(123)
data.df=data.frame(gene=c("APC","NF2","APC","NF2","APC","NF2","APC","NF2"),
                   variable=c("lab01","lab01","lab03","lab03","lab10","lab10","chr","chr"),
                   value=c(sample.int(100, 6),5,22))

ggplot(data.df, aes(x=factor(variable, level = c("chr",paste0("lab",c("01","03","10")))),
                    y=factor(gene, level = c("NF2","APC")))) + 
  geom_tile(data=filter(data.df,variable != 'chr'), 
            aes(fill= value),colour='white') +  
  geom_point(data = filter(data.df,variable=="chr"),
             aes(col=as.factor(value)))+ 
  scale_fill_viridis_b()

在此處輸入圖像描述

暫無
暫無

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

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