首页 > 解决方案 > 修复使用 mutate 函数和 ggplot 时 X 标签的顺序

问题描述

我正在尝试使用 tidyverse 包创建基于文本的热图。尽管我能够生成热图,但 X 标签并未按照我的数据中提供的方式排列。

我想拥有我提供的 X 标签。虽然我确实找到了一些解决方案,但不知何故我无法在我的代码中应用它们。我也不想对因子函数中的列进行硬编码。代码如下:

df <- read.table('Mydata_sheet_test.txt', sep="\t", header=TRUE)
df %>% 
  gather(col, Value, -Sample_names) %>% 
  mutate(row = factor(Sample_names, levels = rev(unique(Sample_names))),
         Value = factor(Value)) %>% 
  ggplot(aes(col, row, fill = Value)) + 
  geom_tile(colour="black") + 
  labs(x = "Chromosome names", y = "samples") + 
  theme(axis.text.x = element_text(angle=21,vjust=0.5)) +
  scale_fill_brewer(palette="Paired")

PS:我仍在学习 dplyr 和数据操作的基础知识,如果有任何简单的解决方案,我很抱歉,我错过了。

主要代码礼貌: Maurits Evers

我的数据如下所示:sample_ID,C1.P,C1.Q,C2.P,C2.Q,C3.P,C3.Q,C4.P,C4.Q,C10.P,C10.Q,C20。 P,C20.Q

sam000086,TLM,TLM,TLM,TLM,3 cp,3 cp,3 cp,3 cp,3 cp,3 cp,3 cp,3 cp

sam000046,,,,,,,,,,,,

sam000028,,,,,,,3 cp,3 cp,3 cp,3 cp,,

sam000092,,3 cp,TLM,TLM,TLM,TLM,3 cp,3 cp,3 cp,3 cp,TLM,TLM

sam000080,,3 cp,TLM,TLM,,,3 cp,3 cp,3 cp,3 cp,3 cp,3 cp

........很快

标签: rggplot2dplyr

解决方案


如果您有或,请更改ggplot(aes(col, row, fill = Value))为。ggplot(aes(as_factor(col), row, fill = Value))tidyverseforcats

否则将其更改为ggplot(aes(factor(col, levels = unique(col)), row, fill = Value)).


推荐阅读