[英]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"))
另一種方法是使用01
和03
而不是1
和3
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.